anon
anon

Reputation: 42597

How to forward declare a C++ class as inheriting from another class?

I know that I can forward declare a class as follows:

class Foo;

// ... now I can use Foo*

However, can I do something like this:

class Bar {
  public:
    virtual void someFunc();
};
// ... somehow forward declare Class Foo as : public Bar here
someFunc(Foo* foo) {
  foo -> someFunc();
}

class Foo: public Bar {
}

?

Thanks!

Upvotes: 0

Views: 742

Answers (2)

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12403

After your forward declaration Foo becomes an incomplete type and it will remain incomplete until you provide the definition of Foo. While the Foo is incomplete any attempt to dereference a pointer to Foo is ill-formed. So to write

foo->someFunc();

you need to provide Foo's definition.

Upvotes: 1

Naveen
Naveen

Reputation: 73443

You can forward declare Bar as class Bar; and change the signature of someFunc to take a Bar* as parameter. Since someFunc() is a virtual method in the base class, it should work.

Upvotes: 4

Related Questions