Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) constructor

 

The constructor is the class element called when a class is created. The class element that is called when a class goes out of scope is called the destructor.

 

#include <iostream>

struct MyClass
{
  MyClass() { std::cout << "Constructor\n"; }
};

int main()
{
  MyClass m; //MyClass constructor called at creation of m
}

 

The code above shows a default constructor: a constructor that has no arguments or only default arguments. Constructors can have multiple arguments. Additionally, a class can have multiple constructors.

 

Avoid calling virtual member functions in constructors and destructors [2].

 

 

 

 

C++98C++11 Constructor initialization

 

Member variables can be initialized in the constructor body, as shown in the example below:

 

struct MyClass
{
  MyClass()
  {
    m_x = 0; //Don't use assignment! Prefer initialization
  }
  MyClass(const int x)
  {
    m_x = x; //Don't use assignment! Prefer initialization
  }
  int m_x;
};

 

Prefer initialization to assignment in constructors [1], as shown in the example below:

 

struct MyClass
{
  MyClass() : m_x(0) {} //Correct!
  MyClass(const int x) : m_x(x) {} //Correct!
  const int m_x;
};

 

Note that the example above, with a const member variable cannot be constructed without the proper constructor initialization shown.

 

 

 

 

 

C++11 delegation

 

Delegation is the technique of constructors calling each other:

 

struct MyClass
{
  MyClass() : MyClass(42) {}
  MyClass(const int x) : m_x(x) {}
  int m_x;
};

int main()
{
  MyClass a;
  MyClass b(1);
}

 

See the page about delegation for more information.

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 48: 'Prefer initialization to assignment in constructors'
  2. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 49: 'Avoid calling virtual functions in constructors and destructors'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict