Constructors are special methods that are called automatically when an object is instantiated, and are never specifically invoked by any function.

We’re motivated by the idea that if we declare some object and never call methods to fill in data (i.e., setAge()), then the data will be uninitialised and thus some garbage value. Constructors are often used to fill initialise the values of member variables.

Basics

For any class A, the default constructor (which does nothing) is generated automatically by the compiler if we don’t define any constructor. If we define constructors, no default constructor is created, which means we would have to define it ourselves.

We can define different constructors with the same name and different parameters, usually if we want to initialise objects differently. We do this with function overloading. Which constructor is called is determined by the argument types when the objects are instantiated. For instance, if we instantiate an object with a string parameter, we’ll use the first constructor in the block directly above. For example, if we define only a constructor with a string input, and we instantiate a new object without any inputs, we get an error — because we didn’t define A().

Definition

Python

In Python, the constructor is given as followed:

def __init__(self, one, two):
	self.first = one
	self.second = two

Those are two underscores on either side of the init. We can pass in parameters like one or two — but often we do without. The self is the absolute minimum that we must pass in.

C++

In C++, constructors must have the same name as the class. They also cannot return a value (i.e., we cannot specify a return type, including void), and they must be public. To define a constructor, see the below.

// in person.h
class Person {
	private:
		string name;
		int age;
	public:
		void setName(string);
		Person();
}
 
// in person.cpp
Person::Person() {
	name = "";
	age = 0;
}

See also