16
class A
{
  A a;//why can't we do this
};
GManNickG
  • 478,574
  • 51
  • 478
  • 539
Suri
  • 3,237
  • 9
  • 42
  • 74
  • 4
    What 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
  • 14
    It's turtles all the way down. – jason Feb 09 '11 at 05:33

6 Answers6

24

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.)

GManNickG
  • 478,574
  • 51
  • 478
  • 539
  • 12
    So what if it is of infinite size? Memory is cheap nowadays! – James McNellis Feb 09 '11 at 05:33
  • 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
23

You can do

class A {
    A* a;
}

because it doesn't require knowing the size of A.

Eran
  • 374,785
  • 51
  • 663
  • 734
Foo Bah
  • 24,723
  • 5
  • 52
  • 79
12

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
};
EboMike
  • 75,005
  • 14
  • 154
  • 164
8
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

Nawaz
  • 341,464
  • 111
  • 648
  • 831
3

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
}
DesignIsLife
  • 490
  • 5
  • 9
3

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;
};
swapnilsj
  • 31
  • 2