I can do this
extern int i;
extern int i;
But I can\'t do the same with a class
class A {
..
}
class A {
..
}
You can declare a class and an object multiple times, what you can't do is define it more than once.
extern
makes this a declaration and not a definition (because there is no initializer):
extern int a;
The body makes your class
a definition and not just a declaration. You can define a class once.
It has nothing to do with declarations vs definitions. The issue is types versus objects.
extern int i;
tells the program that at an object of type int
exists, and its name is i
. Because it is extern
no storage is allocated for it here, but somewhere else, probably in another translation unit, it is defined and storage is allocated for it.
class A {
..
};
defines a type named A
. It doesn't allocate any objects or variables. It makes absolutely no difference at runtime, and no storage is allocated for it, because it is not an object. It simply introduces a new type to the compiler. From this point on, you are able to create objects of type A
, and they will have storage allocated for them.
The following are declarations:
extern int i;
class A;
And the next two are definitions:
int i;
class A { ... };
The rules are:
I gave it some thought. I realized class in not a data type, it is a enabler for defining a data type.
So in
extern int i;
extern int i;
int is a data type. So we are re-declaring a variable not a data type.
But in
class A {...};
class A {...};
A is a data type. And we are re-defining a data type, which is not allowed, of course.
you can do
class A;
as often as you want and then in one file define it with
class A { ... }
Example for this:
classB.h:
class A;
class B { A *a; }
classA.h:
class B;
class A { B *b; }
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.