Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Call subclass method from superclass

I have code of the following style:

class SubClass;
class SuperClass;

class SuperClass {

private:

    void bar() {

        SubClass().foo();
    }
};

class SubClass : SuperClass {

public:

    void foo() {};
};

So basically I have a SuperClass from where I want to call a method foo() of the subclass. VS 2012 gives me the following errors:

Error 1 error C2514: 'SubClass' : class has no constructors.

Error 2 error C2228: left of '.foo' must have class/struct/union.

What is the correct structure for what I want to do?

like image 948
ChrisGeo Avatar asked Dec 20 '22 07:12

ChrisGeo


1 Answers

You can't do this. You must (at least) declare the method in the base class. For example:

#include <iostream>

class SuperClass 
{
public:
    void bar() 
    {
        foo();
    }
private:
    virtual void foo() // could be pure virtual, if you like
    {
        std::cout << "SuperClass::foo()" << std::endl;
    }
};

class SubClass : public SuperClass // do not forget to inherit public
{
public:
    virtual void foo() { std::cout << "SubClass::foo()" << std::endl; }
};

int main()
{
    SuperClass* pTest = new SubClass;

    pTest -> bar();

    delete pTest;
}

will print SubClass::foo().

like image 70
Kiril Kirov Avatar answered Dec 24 '22 01:12

Kiril Kirov