开发者

why can't we declare object of a class inside the same class?

class开发者_如何学JAVA A
{
  A a;//why can't we do this
};


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


You can do

class A {
    A* a;
}

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


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
};


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


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
}


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;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜