operator overloaeded inheritance
Every book says that if you overload an operator(but =) in base class , you could use it in any derived class.
How do I use the point::operator+(point) with objects of type point1 ?
Code:
#include <cstdlib>
#include <iostream>
using namespace std;
class point
{
int x,y;
public:
point(void)
{
}
point(int Ix, int Iy)
{
x = Ix;
y = Iy;
}
void show(void) const
{
cout << "x = " << x << " y = " << y << endl;
}
point operator+(point p)
{
point ret;
ret.x = x + p.x;
ret.y = y + p.y;
return(ret);
}
};
class point1 : public point
{
public:
point1(void):point()
{
}
point1(int Ix, int Iy):point(Ix,Iy)
{
}
point1(point &pin)
{
(*this) = (point1)pin;
}
point1 operator+(point1 p)
{
point pcur = (point)(*this);
point pon = (point)p;
point pans = pcur+pon;
// Until this line everthing is good
// then he says
// "no matching function for call to `point1::point1(point&)'
//
// so I tried point1::point1(point &pin)
// and everthing crashes !!!
return( (point1)(pans));
}
};
int main(void)
{
point1 p1(2,3);
point1 p2(18, 47);
point1 p3;
p3 = p1+p2;
p3.show();
system("PAUSE");
return EXIT_SUCCESS;
}
Yes, but not What I wanted.
Quote:
Originally Posted by grumpy
Code:
class point1 : public point
{
public:
point1 operator+(const point1 &p) const
{
point1 pcur(*this);
pcur.point::operator+(p); // or pcur.point::operator+((const point &)p);
// other stuff specific to point1 addition
return pcur;
}
};
I wanted for point1::operator+ to behave just like point::operator+.
This is not what your point1::operator does, because you return pcur, which operate on the +.
For example :
Code:
point1 p1(2,3), p2(8,7), p3;
p3 = p1+p2;
I would like p3.x = 10 and p3.y = 10.
Your code does p3.x = 2 and p3.y = 3 which is p1 !