Question

I am trying to send a derived pointer to a base class's function through another one of the Base class's functions, but for some reason, it complains: error: invalid use of incomplete type 'struct Derived' on line 8.

#include <iostream>
using namespace std;
class Derived;

class Base
{
public:
    void getsomething(Derived *derived){derived->saysomething();} //This is line 8
    void recieveit(Derived *derived){getsomething(&*derived);}
};

class Derived : public Base
{
public:
    void giveself(){recieveit(this);};
    void saysomething(){cout << "something" << endl;}
};


int main()
{
    Base *b = new Base;
    Derived *d = new Derived;
    d->giveself();
    return 0;
}

do you know how I could fix this?

Was it helpful?

Solution

You can't use forward declaration, when the compiler needs information about the class's members.

A forward declaration is only useful for telling the compiler that a class with that name does exist and will be declared and defined later.

So do like following :

class Derived ;

class Base
{
public:
    void getsomething(Derived *derived); 
    void recieveit(Derived *derived);
};

class Derived : public Base
{
public:
    void giveself(){recieveit(this);};
    void saysomething(){cout << "something" << endl;}
};

void Base::getsomething(Derived *derived){derived->saysomething();} 
void Base::recieveit(Derived *derived){getsomething(&*derived);}

OTHER TIPS

The only way is to take the function definitions out of the class declaration and put them after the declaration of Derived. At the point you're trying to use them, the poor compiler doesn't even know what methods exist on Derived yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top