0

Please,look at this simple class:

class TernaryPolynomial;
class IntegerPolynomial;

class DenseTernaryPolynomial:public IntegerPolynomial,public TernaryPolynomial
{
 public:
 DenseTernaryPolynomial();
static DenseTernaryPolynomial generateRandom(int,int,int);
};

Can you please explain me why does the compiler complains that TernaryPolynomial must be a previously defined class or struct? I thought it shouldn't care at all since i put a forward declaration of that class. Here's the TernaryPolynomial class

class Polynomial;
class IntegerPolynomial;

class TernaryPolynomial:public Polynomial
{
 public:
 TernaryPolynomial();
 virtual ~TernaryPolynomial();
 virtual IntegerPolynomial toIntegerPolynomial() = 0;
 };
Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161

2 Answers2

7

For derivation a forward declaration is not enough, you need to include the full class definition.

Forward declarations can only be used when you define a pointer or a reference to the class as a member or method parameter. As soon as you really begin using things (by dereferencing, accessing a member over a reference or deriving for example) you need to include the whole class definition.

jdehaan
  • 19,700
  • 6
  • 57
  • 97
2

Forward declarations are only useful if you declare a pointer to the class. In this case, the full class definition is not needed.

Deriving from a class makes a is-a relationship. DenseTernaryPolynomial cannot be something it has no knowledge of, other than that it exists.

The sizeof for DenseTernaryPolynomial must be know by the end of the class definition, as well as all members (inherited or not), but a forward declaration doesn't provide this information.

For inheritance, you must include the header where the base class is defined.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625