class A
{
A a;//why can't we do this
};
-
6What would happen when such a class is instantiated? It would construct an A, which constructs another A, and so on, until the end of time. So, yeah, a constructor that makes a stack overflow isn't a good thing. Oh, yeah, and the instance would have an infinite size. – Etienne de Martel Feb 09 '11 at 05:32
-
16It's turtles all the way down. – jason Feb 09 '11 at 05:33
6 Answers
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.)

- 494,350
- 52
- 494
- 543
-
12
-
2@James: Reminds me of the guy who wanted to write a program that creates every possible word of up to 23 letters and didn't flinch when I told him he'd need over a million TB hard disks for that... – EboMike Feb 09 '11 at 05:42
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
};

- 76,846
- 14
- 164
- 167
-
-
1@AjaySinghNegi sizeof(*a) is the size of a pointer, so most likely 4 or 8 bytes depending on your architecture. – EboMike Jul 27 '19 at 15:30
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

- 353,942
- 115
- 666
- 851
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
}

- 510
- 5
- 11
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;
};

- 31
- 2