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++?
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.
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";
    }
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With