12th Computer Science BCA CBSE JAC

Constructor and Destructor in C++ with Example

Constructor and Destructor in C++ with Example
Written by AIPS

In this topic we will learn best concept of Constructor and Destructor in C++ with example.

Constructor

  • It is a special member function which is used to initialize data members of a class.
  • Constructor is different from all other member functions because it’s name matches with class name and automatically called by compiler when object is created.
  • It is similar to other member functions i.e it can be defined inside or outside of the class and can also be passed parameters.

Characteristics of Constructor

  • Constructor has the same name as its class name.
  • Constructor should be declared in public section.
  • Constructor does not return any type not even void.
  • Constructor is used to initialize the data member of a class.
  • Constructor is automatically called when object is created.
  • Constructor can be overloaded i.e multiple constructors can be used in a class.
  • It allows passing parameters.
  • It follows all the access rules which followed by other member functions.
  • It can’t be virtual.
  • if a constructor is not defined in the class then default constructor is automatically generated by the compiler.

Types of Constructor

There are three types of constructors in c++.

  1. Default constructor
  2. Parameterized constructor
  3. Copy constructor

Default constructor

A constructor without parameter or Argument is known as default constructor.

class num

{

public:

num()

{

// default constructor

}

};

About the author

AIPS

Leave a Comment