Cpp - Constructor and Destructor


Classes have a special member function called a constructor.

It is called when an object of the class is instantiated.

The constructor creates a valid object of the class, which often includes initializing its member data.

The constructor is a function with the same name as the class but no return value.

Constructors may or may not have parameters.

Here's a constructor for the Cart class:

Cart::Cart(int initialSpeed) 

This constructor sets the initial value of the speed member variable using a parameter.


Destructors clean up after objects and free any memory that was allocated for them.

A destructor always has the name of the class preceded by a tilde ~.

Destructors take no parameters and have no return value. Here's a Cart destructor:

    // do nothing 

Related Topics