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++?
1 Answer
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 throughsuper()
.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";
}
};
__init__
does not run when a class is declared. It's run whenever ne instance of that class is created.