English

Constructors and Destructors

Advertisements
  • Introduction to Constructors and Destructors 
  • Parametrised constructors 
  • Default Constructors 
  • Copy Constructors 
  • Static members
  • Constructors and Destructors in derived Classes

Constructors and Destructors

Constructors & It’s Syntax Rules 

A constructor is a special member function for automatic object initialization, executed when an object is created. Unlike other member functions, it initializes variables, constructing the values of class data members. 

Syntax Rules: 

  1.  A constructor name must be the same as that of its class name. 
  2.  It is declared with no return type. 
  3.  It may not be static or virtual.  
  4.  It should be public. Only in rare circumstances can it be private.

Constructor with Default Arguments 

It is possible to define constructor with default arguments. 

 For example: The constructor complex ( ) can be declared as : 

 complex (float real, float imag = 0);  

The default value of the argument imag is zero. 

Parameterized & Default Constructor    

It is possible in C++ to pass arguments to the constructor function when the objects are created. These constructors are called parameterized constructors. There may be multiple constructors in same class, but all constructors should have different argument list.  

The default constructor is different from constructor with default argument. The default constructor is a special member function which is invoked by the C++ compiler without any argument for initializing the objects of a class. 

Dynamic Initialization of objects 

Class objects can be initialized dynamically. i. e. the initial value of an object may be provided during runtime. One advantage of dynamic initialization is that we can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different data formats at runtime. 

Copy Constructor 

Copy constructors are always used when the compiler creates a temporary class object.  The general format of the copy constructor is: 

Class - name :: class - name (class - name & ptr) 

Destructors 

A destructor is a function that automatically executes when an object is destroyed. A destructor function gets executed whenever an instance of the class to which it belongs goes out of existence. The primary usage of the destructor function is to release space. Syntax rules for writing a destructor function : 

  1. The destructor function name is same as that of the class it belongs to except that the first character of the name must be a tilde (~). 
  2. It is declared with no return types since it cannot ever return a value.
  3. It takes no arguments.
  4. It should have public access in the class declaration.
If you would like to contribute notes or other learning material, please submit them using the button below.
Advertisements
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×