Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ polymorphism, function calls

Okay, I'm pretty inexperienced as a programmer, let alone in C++, so bear with me here. What I wanted to do was to have a container class hold a parent class pointer and then use polymorphism to store a child class object. The thing is that I want to call one of the child class's functions through the parent class pointer. Here's a sort of example of what I mean in code:

class SuperClass
{
public:
    int x;
}

class SubClass : public SuperClass
{
public:
    void function1()
    {
        x += 1;
    }
}

class Container
{
public:
    SuperClass * alpha;
    Container(SuperClass& beta)
    {
        alpha = beta;
    }
}

int main()
{
    Container cont = new Container(new SubClass);
}

(I'm not sure that's right, I'm still really shaky on pointers. I hope it gets the point across, at least.)

So, I'm not entirely sure whether I can do this or not. I have a sneaking suspicion the answer is no, but I want to be sure. If someone has another way to accomplish this sort of thing, I'd be glad to hear it.

like image 217
moai Avatar asked Sep 19 '26 19:09

moai


1 Answers

Definitely possible. Just a few small changes to your code should get this to work. You need to change the base class (SuperClass) to have a virtual method with the same 'signature' as the derived class (SubClass). You also need to change the Container constructor to take a pointer to the SuperClass instead of a reference. I believe that is all that should be necessary to get this to work.

EDIT: Attempted to include the suggestions in the comments. Good points. Hopefully I didn't mess this up too badly!

class SuperClass
{
public:
    int x;

    // virtual destructor ensures that the destructors of derived classes are also
    // invoked
    virtual ~SuperClass() { }

    // abstract virtual method to be overriden by derived classes
    virtual void function1() = 0;
}

class SubClass : public SuperClass
{
public:
    ~SubClass()
    {
    }

    void function1()
    {
        x += 1;
    }
}

class Container
{
public:
    SuperClass * alpha;
    Container(SuperClass* beta)
    {
        alpha = beta;
    }

    ~Container()
    {
       // Note, this will invoke the destructor of the SubClass class because 
       // SuperClass's destructor is marked as virtual.
       delete alpha;
    }
}

int main()
{
    Container* cont = new Container(new SubClass());
    delete cont;
}
like image 63
Andrew Garrison Avatar answered Sep 22 '26 09:09

Andrew Garrison