c++ constructor programming

C++ programming constructors

 

A constructor has the same name as the class and it doesn’t have any return type. It is invoked whenever an object of the class is created.


Syntax:

/*.....class with constructor..........*/
class class_name
{
    .........
public:
    class_name(); //constructor declared//
    .........
};
class_name :: class_name() //constructor defined
{
      //constructor function body
}

Types of c++ constructors

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

Default constructor


If no constructor is defined in the class then the compiler automatically creates one for the program. This constructor which is created by the compiler when there is no user defined constructor and which doesn’t take any parameters is called default constructor.

Format of default constructor


/*.....format of default constructor..........*/
 class class_name
 {
  .........
   public:
       class_name() { }; //default constructor
       .........
 };

Comments