Why can't I multi-declare a class

The following are declarations:

extern int i;
class A;

And the next two are definitions:

int i;
class A { ... };

The rules are:

  • a definition is also a declaration.
  • you have to have 'seen' a declaration of an item before you can use it.
  • re-declaration is OK (must be identical).
  • re-definition is an error (the One Definition Rule).

The closest equivalent to extern int i with a class is a forward declaration, which you can do as many times as you like:

class A;

class A;

class A;

class A{};

When you define the actual class you are saying how much memory is required to construct an instance of it, as well as how that memory is laid out. That's not really the issue here, though.


The first (extern) makes a reference to an existing variable. So you are just indicating the variable twice.

The class declaration gives meaning to a type (your class: A). You are trying to give two meanings to A. This is not of any use for you, and can only confuse, so the compiler protects you from it.

Btw, if you put both classes in difference namespaces you can give them the same name.

Tags:

C++