CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2012
    Posts
    127

    Overloading [] operators.

    Regards assignment of the exercise the project should contain two [] operators
    declaration which are

    const Point& operator [] (int index) const;
    Point& operator [] (int index);

    The goal making two are for reading and writing elements...
    So project compile well.
    However, during compilation I don't see anyone message from
    const Point& operator [] (int index) const; So I mean that the operator didn't call during project.

    All work did -> Point& operator [] (int index).
    ... but all elements read and write correctly

    What did I do wrong?

    Code:
    //array.hpp // A header file for the Array class to your current project.
    #ifndef Array_HPP
    #define Array_HPP
     
    #include "Point.hpp"
    #include <iostream>
    
    class Array
    {
    private:	
    
        Point* m_data;		    		// A data member for a dynamic C array of Point objects (Point* m_data).
        int m_size;			    		// A data member for the size of the array.
    
    public: 
    
        //----------- Declaration of Constructors -----------//
        Array::Array();						   // Default constructor
        Array::Array(const int new_size);		           // Constructor with size argument.
    	Array::Array(const Array& ObjArray);		   // Copy constructor
      
    	//----------- Declaration of Modificator(s) member functions -----------//
    	void   SetElement(const Point& pt, int index);			// Set Element to a Array object
    
    
    	//----------- Declaration of Operators Overloading the class's members -----------//
    	Array& operator =  (const Array& source);				// Overloading Assignment operator.
        Point& operator [] (int index);							// Return a reference to needed m_data. Using for writing 
    	const Point& operator [] (int index) const ;			// Return a reference to needed m_data. Using for reading
     
    
        //----------- Declaration of Global (friend) Ostream << Operator  -----------//
        friend std::ostream& operator << (std::ostream& os, const Array& ar);			// Overloading << operator
     
    }	/*!!!*/; /*!!!*/
    #endif // Array_HPP
    Code:
    #ifndef Point_HPP // anti multiply including gates
    #define Point_HPP
    
    #include <string>
    #include <iostream>
    #include <sstream>
    
    class Point
    {	
    	private:		//  declaration of private data members 
    	double x;		// X coordinate
    	double y;		// Y coordinate
    
    	public:			// public declaration of data members (in given example haven't ) and member functions 
    
    
    		//----------- Declaration of Constructors -----------//
    	Point();										// Default constructor
    	Point(double newX , double newY);				// Constructor 
    	explicit Point(double value /*, double newY*/);			// Second Constructor 
    	Point (const Point& ObjectOfClassPoint);		//COPY constructor
    	~Point(); // 
    
    	//----------- Declaration of  Accessors member functions -----------//
    	std::string ToString() const;    
    	double X() const;					
    	double Y() const;	
    
    	//----------- Declaration and  of and Implementaion of setters member functions -----------//
    	void X(double newX) {x = newX;};	// The x-coordinate
    	void Y(double newY) {y = newY;};	// The y-coordinate
    
    	//----------- Declaration of Global Ostream << Operator  -----------//
    	friend std::ostream& operator << (std::ostream& out, Point const& ObjPoint); 
    	friend std::ostream& operator << (std::ostream& out, Point const *objPoint);
    	
    }	/*!!!*/; /*!!!*/
    
    //----------- Implementaion (inline) of getters member functions -----------//
    
    inline	double Point::X() const {return x;};					
    inline	double Point::Y() const {return y;};	
    
    #endif // Point_HPP
    Code:
    //Array.cpp
    #include "Array.hpp"
                                            
    	//----------- Implementation of Constructors -----------//
    	Array::Array() :  m_size(10), m_data(new Point[m_size])                                    
    			{
    				std::cout << "Array Default Constructor was called " ;
    			}
    
    	Array::Array(const int new_size) :m_size(new_size), m_data(new Point[m_size])       //specified by the size input argument
    									
    			{	
    
    				std::cout << "Array Constructor was called "; 
    			}
    
    	Array::Array(const Array& ObjArray) 
    {
    	
    
        std::cout << "Array copy Constructor "; 
     
        m_size    =    ObjArray.m_size;		// shallow copy - this is not dynamic alloc
     
        if (ObjArray.m_data)				// if not zeros then there is a ref. - Deep copy needed
        {
            std::cout <<"im on Copy Constructor was called ";
     
            m_data = new Point[ObjArray.m_size];
     
            for (int i = 0; i <	ObjArray.m_size; i++)
                m_data[i]    =    ObjArray.m_data[i];
        }
        else
            m_data = 0;						//NULL
    }
    
    	
    
    
    	//----------- Declaration and  of Modificators member functions -----------//
    	void Array::SetElement(const Point& ObjPoint, int index)
    		{	// • Add a SetElement() function that sets an element. 
    			// When the index is out of bounds, ignore the “set”. 
    			// We will add better error handling later.
        
    			if (index <= m_size) // When the index is out of bounds, ignore the “set”. 
    			{
    				m_data[index] = ObjPoint;
    				std::cout << "Set Element " << ObjPoint  << std::endl;
    			}
    			else 
    				std::cout << "The Element with index [ "<< index << " ] and\ndata ( " << m_data <<  " ) wasn't setted. "
    			 << " Ignore the set" <<  std::endl;
    		}
    
    	//----------- Declaration and  of Modificators member functions -----------//
    	void Array::SetElement(const Point& ObjPoint, int index)
    		{	
        
    			if (index <= m_size) // When the index is out of bounds, ignore the “set”. 
    			{
    				m_data[index] = ObjPoint;
    				std::cout << "Set Element " << ObjPoint  << std::endl;
    			}
    			else 
    				std::cout << "The Element with index [ "<< index << " ] and\ndata ( " << m_data <<  " ) wasn't setted. "
    			 << " Ignore the set" <<  std::endl;
    		}
    
    
    
    	//----------- Implementation of Operators Overloading the class's member -----------//
    	const Point& Array::operator [] (int index) const
    {	
    
        std::cout << " []  operator for reading was called " ; 
     
        if (index > this->m_size)
    	{
            std::cout << "OUT OF BOUND ";
            return this->m_data[0];
    	}
        return m_data[index];
    }
    
    	Point& Array::operator [] (int index)
    		{	
    
    			std::cout << "[] operator for writing was called \n" ; 
     
    			if (index > this->m_size)
    			{
    				std::cout << "OUT OF BOUND \n" ; 
    				return this->m_data[0];
    			}
    			return m_data[index];
    
    
    
    		}
    
     
    	Array& Array::operator = (const Array& source)
    		{
    			
    
    			std::cout << " In the Array Assignment operator\n";
     
    			if (this == &source)
    				{
    				std::cout << "Same Array \n"; 
    				return *this;
    				}
     
    			delete [] m_data;
    			std::cout << "Deleted m_data array\n";
     
    			m_size = source.m_size;								// shallow copy - this is not dynamic alloc
     
    			if (source.m_data)									// if not zeros then there is a ref.
    			{
    				std::cout <<"im here\n"; 
     
    				m_data = new Point[source.m_size];				// create a new pointee.
     
    				for (int i = 0; i < source.m_size; i++)
    					m_data[i]    =    source.m_data[i];			//copy the points from/to array
    			}
    			else
    				m_data = 0;  //NULL
     
    			return *this;
    		}
    
    	
    
    
    	//----------- Implementation of GLOBAL(friend) Ostream << Operator  -----------//
    std::ostream& operator << (std::ostream& os, const Array& ObjArray)
    {
    	os << "\nArray Size = " << ObjArray.m_size << std::endl;
     
    		for (int i = 0; i < ObjArray.m_size; i++)
    			os << "Array [" << i << "]= "<< ObjArray.m_data[i] << "\n";
     
        return os;
    }
    Code:
    #include "Point.hpp"
    
    			//----------- Implementation of Constructors -----------//
    
    	Point::Point() : x(0) , y(0)														// Default constructor (implemented using colon syntax )
    		{ 
    		//	std::cout << "hi my default constructor\n\n\t";
    		}							
    
    	Point::Point(double newX , double newY) : x(newX)  , y(newY)						// Constructor 
    		{ 
    			//std::cout << "hi my constructor\n\n\t"; 
    		}				
    
    	Point::Point(double value /*, double newY*/) : x(value)  /*, y(newY)	*/			// Second Constructor 
    		{ 
    		//std::cout << "hi my constructor\n\n\t"; 
    		}	
    
    	Point::~Point() 																	// Destructor
    		{
    			//std::cout << "bye my point..\n";
    		}									 
    
    	Point::Point (const Point& ObjectOfClassPoint)										// Copy constructor
    		{
    			
    			x = ObjectOfClassPoint.x;
    			y = ObjectOfClassPoint.y;
    		}
    		
    			//----------- Implementation of Accessor(s) member functions -----------//
    
    	std::string Point::ToString() const
    		{
    			
    			std::ostringstream os;								  // std::stringstream object
    			os << " Point (" << x << ", " << y << ")";			  // customization of output 
    			return os.str();									  
    		}
    
    	//----------- Implementation of GLOBAL Ostream << Operator  -----------//
    
    	std::ostream& operator << (std::ostream& out, Point const& ObjPoint)
    {
      
    
    	return out << "[" << ObjPoint.x << "," << ObjPoint.y << "]" ; 
    	
    }
    
    		std::ostream& operator << (std::ostream& out, Point const *objPoint)
    {
      
    	return out << "[" << objPoint->x << "," << objPoint->y << "]" ; 
    	
    }
    Code:
    //main.cpp
    
    #include <iostream>
    #include "Point.hpp"
    #include "Array.hpp"
    
    
    
    int main()
    
    	{
    
        int i = 0;                                              
        int size_of_array = 5;                                      
        Point** MyArrayOfPointers;
    	MyArrayOfPointers = new Point*[size_of_array];						//Creating an array of Point pointers with 3 elements on the heap.
    	
    	int some_data_for_x[5] = {1830 , 1901 , 1914, 1900 , 1895} ; 
    	int some_data_for_y[5] = {1903 , 1947 , 1211, 1969 , 1789} ; 
     
       
        for (i = 0 ; i <size_of_array; i++ )								// Create for each element in the array a point on the heap.
    		{
    			MyArrayOfPointers[i] = new Point(some_data_for_x[i],				
    												some_data_for_y[i]);																						
    		}
       
    	std::cout << "\n\t Setting elements of MemoryManagerArray \n";
    
        Array* MemoryManagerArray = new Array(size_of_array); 
        MemoryManagerArray->SetElement(*MyArrayOfPointers[0],0);				// Setting elements of MemoryManagerArray
        MemoryManagerArray->SetElement(*MyArrayOfPointers[1],1);
    	MemoryManagerArray->SetElement(*MyArrayOfPointers[2],2);
    	MemoryManagerArray->SetElement(*MyArrayOfPointers[3],3);
    	MemoryManagerArray->SetElement(*MyArrayOfPointers[4],17);				// The set will be ignored, because out of bounds
      
    	std::cout << "\n\t ---TEST OF [] operator--- \n";
    
    	Array* SquareBracktsTESTArray = new Array(size_of_array);
    	SquareBracktsTESTArray->SetElement(*MyArrayOfPointers[0],0);						// Setting elements to Array 
    	SquareBracktsTESTArray->SetElement(*MyArrayOfPointers[1],1);
    	SquareBracktsTESTArray->SetElement(*MyArrayOfPointers[2],2);
    	SquareBracktsTESTArray->SetElement(*MyArrayOfPointers[3],3);
    	SquareBracktsTESTArray->SetElement(*MyArrayOfPointers[4],4);
     
    	std::cout << "\nSquareBracktsTESTArray [] operator TEST\nReading a element from a given place : \n\n" 
    			  << (*SquareBracktsTESTArray)[0] << "\n"
    			  << (*SquareBracktsTESTArray)[1] << "\n"
    			  << (*SquareBracktsTESTArray)[2] << "\n"
    			  << (*SquareBracktsTESTArray)[3] << "\n"
    			  << (*SquareBracktsTESTArray)[4] << "\n"
    			  << std::endl;
    
    	std::cout << "\nSquareBracktsTESTArray [] operator TEST.\nWriting a element to a given place : \n\n" ;
    
    	std::cout << "Now [] operator we write [4] and [3] element from place [0] : " ; 
    
    	(*SquareBracktsTESTArray)[4] = *MyArrayOfPointers[0]; 
    	(*SquareBracktsTESTArray)[3] = *MyArrayOfPointers[0]; 
    	
    			  std::cout << "\n Read again using [] operator:  \n" ;
    				 (*SquareBracktsTESTArray)[0].ToString(); 
    			  std::cout << (*SquareBracktsTESTArray)[1] << "\n"
    			  << (*SquareBracktsTESTArray)[2] << "\n"
    			  << (*SquareBracktsTESTArray)[3] << "\n"
    			  << (*SquareBracktsTESTArray)[4] ; 
    
    
    	
        
    	std::cout << std::endl; 
        return 0;
    
    }

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Overloading [] operators.

    Quote Originally Posted by oteel View Post
    Regards assignment of the exercise the project should contain two [] operators
    declaration which are

    const Point& operator [] (int index) const;
    Point& operator [] (int index);

    const Point& operator [] (int index) const; So I mean that the operator didn't call during project.
    It isn't called because you don't have code that requires a const Array.
    Code:
    void SomeFunction(const Array& theArray)
    {
        theArray[0];
    }
    You will see that the only way to call this function is to have a const version of operator []. If you want proof, remove the const version of Array::operator[] and you will see that the code will not compile.

    Also, your code is faulty. I can easily break it by doing this:
    Code:
    Array a(0);
    Point p = a[0];
    And the reason it doesn't work is this:
    Code:
    if (index > this->m_size)
    {
        std::cout << "OUT OF BOUND \n" ; 
        return this->m_data[0];
    }
    What if there are no elements? How can you return data for the first element when there are no elements?

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; July 28th, 2012 at 03:29 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured