Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of Python's __init__

Tags:

c++

python

While learning to code in C++, in a lot of situations I need code to run when I declare the class like giving variables values. I know in Python you can just use __init__, but how would I do this in C++?

like image 929
IDontKnowWhatToPutAsMyUsername Avatar asked Mar 08 '23 06:03

IDontKnowWhatToPutAsMyUsername


1 Answers

The equivalent of Python's __init__ method in C++ is called a constructor. The role of both is to initialize/construct instance of class to be usable. There are some differences, though.

  • In Python, data members are initialized inside __init__, whereas in C++ they should be initialized using an initializer-list.

  • In C++, a constructor by default chains to the default constructor of the parent class, whereas in Python you have to explicitly call the parent __init__, preferably through super().

  • C++ allows function overloading, which extends to constructors. That allows to declare different constructors with different signatures (argument lists). To do the same in Python you have to declare __init__ as accepting *args,**kwargs and manually dispatch based on those.

  • In C++ there are spacial kinds of constructors, namely default constructor, copy constructor and move constructor.

Example

Python:

class Foo:
    def __init__(self, x):
        self.x = x
        print "Foo ready"

C++:

class Foo {
public:
    int x;
    Foo(int x) : x(x)
    {
        std::cout << "Foo ready\n";
    }
};
like image 101
el.pescado - нет войне Avatar answered Mar 20 '23 22:03

el.pescado - нет войне