hsienting
hsienting

Reputation: 71

problem with an abstract type as class member variable

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?

Upvotes: 0

Views: 2527

Answers (1)

johnsyweb
johnsyweb

Reputation: 141810

POINT declares:

   virtual int point_dim() const = 0;

Therefore POINTX must have a const method called point_dim:

   int point_dim() const {return 10;}

Without this, it will have two point_dim() methods, one non-const and one const but pure virtual, leaving POINTX as abstract.

As long as func() takes a reference to a POINT:

int func(const POINT& pt)
{
    const int dim = pt.point_dim();
    // ...
}

You'll be able to call it like this:

func(*space.m_point);

Also, note that you don't need the C-style cast here:

space.m_point = ptx;

And don't forget to delete ptx when you're done!

Upvotes: 2

Related Questions