class A
{
A a;//why can\'t we do this
};
You can do
class A {
A* a;
}
because it doesn't require knowing the size of A.
This is the way you can have a pointer to object of class A and this way it is not required to know the size of class A before it is declared at compile time.
class A {
A* a;
};
A a;//why can't we do this
Because A
is an incomplete type, as it has not been defined yet, rather it's being defined. And the compiler needs to know the complete type of A
when it sees it inside class A
, and since A
is incomplete, it cannot determine it's size, it cannot determine how much space the member variable a
is going to take, therefore it will not compile it.
But since size of a pointer is well-known to the compiler, no matter what type of pointer it is. You can define a pointer in your class like this:
class A
{
A *pA; //okay since sizeof(pA) == sizeof(void*) == well-known to the compiler!
};
Online Demo : http://www.ideone.com/oS5Ir
I take it you're coming from Java or something? A a
will create a full instance of type A
, which, well, contains A
, which contains A
, which contains A
.
You're probably thinking about this:
class A
{
A *a; // A pointer to A, not a full instance
};
In C++ :
You can not do this, As it will be recursive structure (no end for calculating object size) , to Overcome this problem,
Use Self Referential Pointer i.e. the Pointer having the address of Same class type.
class A
{
A* aObj; // Self Referential Pointer
}
Because the class would be infinite in size.
(This is done language-wise by specifying you can't have incomplete types as members, only reference or pointers to them, and that A
is an incomplete type until the end of the class definition.)