-1

i made a class in c++ and it had a member of the same class and it gave a incomplete type class error.

class A{
    private:
        A member;
};

i found these "Incomplete type" in class which has a member of the same type of the class itself ,Incomplete Type these gave a very good explanation as to why the error happened and how to fix it.

but for practice i made the same code on python 2.7 and it was able to make a class with a member of the same class.

my question is HOW(whats the explanation) python is able to do that, and possible difference between c++ and python on handling this particular problem

python code:

class node:
    def __init__(self,t):
        self.key=t
        self.lc=None
        self.rc=None

parent=node(10)
lc=node(5)
rc=node(15)
parent.lc=lc
parent.rc=rc
Community
  • 1
  • 1
Nikhil
  • 71
  • 7

2 Answers2

1

Python has duck typing and doesn't actually create the member object before your call to its constructor.

In Python your variable can even contain a string and then later a class object. I don't see how you would have 'the same code'. You don't specify the type of your variables and they can contain whatever you want, only raising errors when wrongly manipulated.

In C++ the member A will be created at the same time as the class, leading to an infinite recursion.

Use a pointer if you want to choose when to allocate the member.

Community
  • 1
  • 1
coyotte508
  • 9,175
  • 6
  • 44
  • 63
1

Are you sure?

>>> class A:
...     aa = A()
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in A
NameError: name 'A' is not defined

I get this in both Python 2.7 and 3.5.

Nick Matteo
  • 4,453
  • 1
  • 24
  • 35