Hi,all and thanks in advance. Shape base class, line and Point derived classes.
What should I declare in .h files and implement in .cpp files that this is array will be work.
My major concern refer to operator [] and assign (=) operator. As far as I understand I should overload ([]) and (=) three times for classes shape , line and point or not... or is it possible made through virtual function? How will be code looks like ?
1 2 3 4 5 6 7 8 9 10 11 12 13
// part of main.cpp
Shape* shapes[3]; // Array of pointers to Shape
shapes[0] = new Shape();
shapes[1] = new Line ("line from array ", Point(1,22),Point(33,22));
shapes[2] = new Point(11,44);
cout << "using ToString function" << endl;
for(int i=0; i < 3; i++)
cout << s[i]->ToString();
for(i=0; i < 3; i++)
delete s[i];
" I do not see where you use the assignment operator." I thought I that I should make code for all classes Point, Line and ect. like code below or it is wrong
Point& Shape::operator = ( Point& source)
{
cout << " In the Array Assignment operator" << endl;
if (this == &source)
{
cout << "Same Array " << endl;
return *this;
}
delete [] m_data;
cout <<"Deleted m_data array" << endl;
m_size = source.m_size; // shallow copy - this is not dynamic alloc
if (source.m_data) // if not zeros then there is a ref. - Deep copy needed
{
cout <<"im here"<<endl;
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;
}
how should see implementation of [] operator ?My code below I think unsuitable in this case. could you help me ?
1 2 3 4 5 6 7 8 9 10 11
Point& Shape::operator [] (int index)
{// My concern refer to Point&. I think it's not correct use this way...
cout << "Array [] operator" << endl;
if (index > this->m_size)
{
cout << "i am hreeeee" << endl;
returnthis->m_data[0];
}
return m_data[index];
}
When it comes to inheritance and pointers then operators like that are pretty useless. Use (virtual) functions instead.
if you want to delete a pointer to the base class then you need a virtual destructor for this base class. Because then the destructors of the sub classes are called otherwise not.