6

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++?

3
  • please make sure to read the comments on your accepted answer, as there are problems with it.
    – xaxxon
    Commented Aug 23, 2017 at 3:02
  • __init__ does not run when a class is declared. It's run whenever ne instance of that class is created. Commented Aug 23, 2017 at 7:38
  • that's what i meant i just didn't know what word to use Commented Aug 24, 2017 at 0:16

1 Answer 1

10

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.