Consider the following classes:
class Coord
{
public:
double _x, _y;
Coord(double x, double y)
{
_x = x;
_y = y;
}
};
class NamedPoint : public Coord
{
public:
int _id;
NamedPoint(int id, double x, double y) :
Coord(x,y),
_id(id)
{
}
};
I’d like to create a member function of NamedPoint — coord() — that returns a reference of type Coord corresponding to the NamedPoint.
For example, I’d like to something like:
const Coord& NamedPoint::coord()
{
return ((Coord)*this);
}
But I get a warning about temporary variables and I’m not crazy about it.
Of course, the following works:
Coord coord()
{
Coord c = *this;
return c;
}
But I’d rather return a reference.
Does anyone know if this is possible using inherited classes?
Sorry for not explaining the point of the function. I’m overloading the == operator differently for Coord and NamedPoint. Coord would simply check {x,y} and NamedPoint would check {id,x,y}. If I forget to cast a NamedPoint to a Coord before this == test, I’ll use the wrong version.
So, while I realize that
(Coord)np1 == (Coord)np2
would give me what I want, I’d rather use something like
np1.coord() == np2.coord()
which I think is more clear as to what is going on.
What’s the point of the function?
NamedPointis implicitly convertible toCoordanyway:Anyway, your function should simply use this conversion: