2

I've created a class that has a bunch of inherited classes (parent classes) so that I can use polymorphism but the problem is that there are two classes that are calling each other.

So I need to forward declare them and I can forward declare one class but when I forward declare the inherited class the compiler says it can't change pointer from one to the other.

Is there a way to make the forward declaration of the inherited class so that it states it inherits from it? Ex:

class Shape;
class Circle:Shape;
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
argetlam5
  • 112
  • 2
  • 10
  • 1
    I suppose you already have read [this article](http://en.wikibooks.org/wiki/C++_Programming/Code/Design_Patterns/Creational_Patterns)? – πάντα ῥεῖ Mar 17 '15 at 19:23
  • Related: http://stackoverflow.com/questions/12902751/how-to-clone-object-in-c-or-is-there-another-solution – R Sahu Mar 17 '15 at 19:23
  • @RSahu ... how is that related? – Yakk - Adam Nevraumont Mar 17 '15 at 19:42
  • possible duplicate of [In which order should classes be declared in C++?](http://stackoverflow.com/questions/757241/in-which-order-should-classes-be-declared-in-c) – Christophe Mar 17 '15 at 19:42
  • 1
    @Christophe so that shows how to forward declare a class. But how does that help with pointer conversion with only the forward declaration, which is the OP's problem? – Yakk - Adam Nevraumont Mar 17 '15 at 19:43
  • @Christophe, it was when the original question asked about creating prototypes - 'How to make a prototype of a class that inherits from another class c++?" – R Sahu Mar 17 '15 at 19:43
  • If you are going to be using `Circle` as an incomplete type after the forward declaration, why do you need the information that it inherits from `Shape` as well? – Pradhan Mar 17 '15 at 19:45
  • Sorry, I lack imagination, but I don't understand the problem of the OP. It would be usefull to show us a MCVE (http://stackoverflow.com/help/mcve) – Christophe Mar 17 '15 at 19:49

1 Answers1

1

You don't need to specify the family tree, after the class name, when making forward declarations.

class Shape;
class Circle;
class Rectangle;

When you declare classes that use inheritance, the compiler would appreciate the full declaration of the parent classes.

A rule of thumb is that the types for declaration of pointers and references can be resolved using forward declarations. Any code that accesses elements of a class via pointers or references needs the complete class declaration.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • In particular, casting from a derived cast to a base class counts as using the class, not just referencing or pointing to the class so you need the full declaration available. – Dale Wilson Mar 17 '15 at 20:06