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?
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()
.
First, you have to realise that calling SubClass().foo()
has nothing to do with the current object - it will create a new SubClass
object and call its foo
member. If you want the bar
function to call foo
on the current object, you need to declare foo
as a virtual function in the base class, as Kiril suggested.
However, if you do want to call foo
on a new object (which doesn't make much sense, but whatever), you are doing it correctly. Your example didn't compile because SubClass
is forward declared, but not defined before bar
function - you might want to move the implementation of bar
below the definition of SubClass
, like so: class SubClass; class SuperClass;
class SuperClass {
private:
void bar();
};
class SubClass : SuperClass {
public:
void foo() {};
};
void SuperClass::bar() {
SubClass().foo();
}
you can try with some CRTP, ie:
#include <iostream>
class SubClass;
template<typename T>
class SuperClass {
public:
void bar() {
((T *) this)->foo();
}
};
class SubClass : public SuperClass<SubClass> {
public:
void foo() {
std::cout << "hello crtp!" << std::endl;
};
};
int main(void){
SubClass a = SubClass();
a.bar();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.