class - C++ Call subclass method from superclass -
i have code of following style:
class subclass; class superclass; class superclass { private: void bar() { subclass().foo(); } }; class subclass : superclass { public: void foo() {}; };
so have superclass want call method foo() of subclass. vs 2012 gives me following errors:
error 1 error c2514: 'subclass' : class has no constructors.
error 2 error c2228: left of '.foo' must have class/struct/union.
what correct structure want do?
you can't this. must (at least) declare method in base class. example:
#include <iostream> class superclass { public: void bar() { foo(); } private: virtual void foo() // pure virtual, if { std::cout << "superclass::foo()" << std::endl; } }; class subclass : public superclass // not forget 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()
.
Comments
Post a Comment