News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

C++ Tutorial – 14 – Constructor

In addition to fields and methods, a class can contain a constructor. This is a special kind of method used to construct, or instantiate, the object. It always has the same name as the class and does not have a return type. To be accessible from another class the constructor needs to be declared in a section marked with the public access modifier.

class MyRectangle
{
 public:
  int x, y;
  MyRectangle();
};
 
MyRectangle::MyRectangle() { x = 10; y = 5; }

When a new instance of this class is created the constructor method will be called, which in this case assigns default values to the fields.

int main()
{
  MyRectangle s;
}

Constructor overloading

As with any other method the constructor can be overloaded. This will allow an object to be created with different parameter lists.

class MyRectangle
{
 public:
  int x, y;
  MyRectangle();
  MyRectangle(int, int);
};
 
MyRectangle::MyRectangle() { x = 10; y = 5; }
MyRectangle::MyRectangle(int a, int b) { x = a; y = b; }

For example, with the two constructors defined above the object can be initialized either with no arguments or with two arguments, which will be used to assign the fields.

// Calls parameterless constructor
MyRectangle r;
 
// Calls constructor accepting two integers
MyRectangle t(2,3);

This keyword

Inside the constructor, as well as in other methods belonging to the object – so called instance methods – a special keyword called this can be used. This is a pointer to the current instance of the class. It can be useful if, for example, the constructor’s parameter names are the same as the field names. The fields can then still be accessed by using the this pointer, even though they are overshadowed by the parameters.

MyRectangle::MyRectangle(int x, int y) 
{ 
  this->x = x; this->y = y;
}

Constructor initialization list

As an alternative to assigning fields inside the constructor, they may also be assigned by using the constructor initialization list. This list starts with a colon after the constructor parameters and is followed by calls to the field’s own constructors. This is actually the recommended way of assigning fields, because it gives better performance than assigning the fields inside the constructor.

MyRectangle::MyRectangle(int a, int b) : x(a), y(b) {}

Default constructor

If no constructors are defined for a class the compiler will automatically create a default parameterless constructor when the program compiles. Because of this, a class can be instantiated even if no constructor has been implemented. The default constructor will only allocate memory for the object. It will not initialize the fields. In contrast to global variables, fields in C++ are not automatically initialized to their default values. The fields will contain whatever garbage is left in their memory locations until they are explicitly assigned values.

Destructor

In addition to constructors, a class can also have a destructor. The destructor is used to release any resources allocated by the object. It is called automatically before an object is destroyed, either when the object passes out of scope or when it is explicitly deleted for objects created with the new operator. The name of the destructor is the same as the class name, but preceded by a tilde (~). A class may only have one destructor and it never takes any arguments or returns anything.

class Semaphore
{
 public:
  bool *sem;
 
  Semaphore()  { sem = new bool; }
  ~Semaphore() { delete sem; }
};

Direct initialization

The object creation syntax that has been used so far is called direct initialization. This syntax can include a set of parentheses which are used to pass arguments to a constructor in the class. If the parameterless constructor is used, the parentheses are left out.

// Direct initialization
MyClass a(5);
MyClass b;

Value initialization

An object can also be value initialized. The object is then created by using the class name followed by a set of parenthesis. The parentheses can supply constructor arguments, or remain empty to construct the object using the parameterless constructor. A value initialization creates only a temporary object, which is destroyed at the end of the statement. To preserve the object it must either be copied to another object or assigned to a constant reference. Assigning the temporary object to a constant reference will maintain the object until that reference goes out of scope.

// Value initialization
const MyClass& a = MyClass();

A value initialized object is almost identical to one created by using direct initialization. A minor difference is that non-static fields will in some cases be initialized to their default values when using value initialization.

Copy initialization

If an existing object is assigned to an object of the same type when it is declared, the new object will be copy initialized. This means that each member of the existing object will be copied to the new object.

// Copy initialization
MyClass a = MyClass();
MyClass b(a);

This occurs because the compiler will automatically create a copy constructor for each class, which is called for these kinds of assignments. The copy constructor takes a single argument of its own type, and then constructs a copy of the specified object. Note that this behavior is different from many other languages, such as Java and C#. In those languages initializing an object with another object will only copy the object’s reference, and not create a new object copy.

New initialization

Finally, an object can be initialized through dynamic memory allocation by using the new keyword. Dynamically allocated memory must be used through a pointer or reference. The new operator returns a pointer, so to assign it to a reference it needs to be dereferenced first. Keep in mind that dynamically allocated memory must be explicitly deleted once it is no longer needed.

// New initialization
MyClass* a = new MyClass();
MyClass& b = *new MyClass();
// …
delete a, b;
Recommended additional reading:
Sams - Teach Yourself C++ in One Hour a Day