Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is it possible to forward declare a class as inheriting from another class?

I know that I can do:

class Foo; 

but can I forward declare a class as inheriting from another, like:

class Bar {};  class Foo: public Bar; 

An example use case would be co-variant reference return types.

// somewhere.h class RA {} class RB : public RA {} 

... and then in another header that doesn't include somewhere.h

// other.h class RA;  class A {  public:   virtual RA* Foo();  // this only needs the forward deceleration }  class RB : public RA; // invalid but...  class B {  public:   virtual RB* Foo();  //  } 

The only information the compiler should need to process the declaration of RB* B:Foo() is that RB has RA as a public base class. Now clearly you would need somewhere.h if you intend to do any sort of dereferencing of the return values from Foo. However, if some clients never calls Foo, then there is no reason for them to include somewhere.h which might significantly speed compilation.

like image 772
anon Avatar asked Jan 29 '10 01:01

anon


People also ask

Can you forward declare in C?

In Objective-C, classes and protocols can be forward-declared if you only need to use them as part of an object pointer type, e.g. MyClass * or id<MyProtocol>.

Can you forward declare base class?

A base class MUST be declared (not forward declared) when being declared as a based class of another class. An object member MUST be declared (not forward declared) when being declared by another class, or as parameter, or as a return value.

Can you forward declare a nested class?

You cannot forward declare a nested structure outside the container. You can only forward declare it within the container.

Can you forward declare a class C++?

In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };


1 Answers

A forward declaration is only really useful for telling the compiler that a class with that name does exist and will be declared and defined elsewhere. You can't use it in any case where the compiler needs contextual information about the class, nor is it of any use to the compiler to tell it only a little bit about the class. (Generally, you can only use the forward declaration when referring to that class without other context, e.g. as a parameter or return value.)

Thus, you can't forward declare Bar in any scenario where you then use it to help declare Foo, and it flat-out doesn't make sense to have a forward declaration that includes the base class -- what does that tell you besides nothing?

like image 190
Joe Avatar answered Sep 23 '22 10:09

Joe