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

后端 未结 6 596
礼貌的吻别
礼貌的吻别 2020-12-01 19:10
class A
{
  A a;//why can\'t we do this
};
相关标签:
6条回答
  • 2020-12-01 19:24

    You can do

    class A {
        A* a;
    }
    

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

    0 讨论(0)
  • 2020-12-01 19:28

    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 讨论(0)
  • 2020-12-01 19:29
    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

    0 讨论(0)
  • 2020-12-01 19:32

    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
    };
    
    0 讨论(0)
  • 2020-12-01 19:33

    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
    }
    
    0 讨论(0)
  • 2020-12-01 19:34

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

    0 讨论(0)
提交回复
热议问题