I try to use a abstract class type as a member variable in my class definition, but somehow it has some problem. Here is the abstract class type:
class POINT{
public:
virtual int point_dim() = 0;
/*other virtual functions...*/
}
And here is the inherited class:
class POINTX : public POINT{
public:
int point_dim(){return 10;}
}
I create another class to use POINT as a member variable, since POINT is a pure virtual class, I can only declare it as a pointer:
class SPACE{
public:
POINT* m_point;
/*some other declarations*/
}
But when I use it in my main, it does not work as I expect:
int main(){
POINTX *ptx = new POINTX();
SPACE space;
space.m_point = (POINT*)ptx;
//some function call use POINT as parameter(pass by reference):
func(*space.m_point, ....);
}
error happened when func(space.m_pint) is invoked. However, if I do this without class SPACE, it’s ok. e.g.:
int main(){
POINTX *ptx = new POINTX();
POINT *m_point = (POINT*)ptx;
//some function call use POINT as parameter(pass by reference):
func(*m_point, ....);
}
Anyone knows what’s wrong?
POINTdeclares:Therefore
POINTXmust have aconstmethod calledpoint_dim:Without this, it will have two
point_dim()methods, one non-constand oneconstbut purevirtual, leavingPOINTXas abstract.As long as
func()takes a reference to aPOINT:You’ll be able to call it like this:
Also, note that you don’t need the C-style cast here:
And don’t forget to
delete ptxwhen you’re done!