C++ Class Default Constructors

Introduction

A constructor is a member function that has the same name as the class.

To initialize an object of a class, we use constructors.

Constructor's purpose is to initialize an object of a class.

It constructs an object and can set values to data members.

If a class has a constructor, all objects of that class will be initialized by a constructor call.

Default Constructor

A constructor without parameters or with default parameters set is called a default constructor.

It is a constructor which can be called without arguments:

#include <iostream> 

class MyClass // w w  w  .  j  a  va  2 s  .c  om
{ 
public: 
    MyClass() 
    { 
        std::cout << "Default constructor invoked." << '\n'; 
    } 
}; 
int main() 
{ 
    MyClass o; // invoke a default constructor 
} 

Another example of a default constructor, the one with the default arguments:

#include <iostream> 

class MyClass //from w  w  w  .  j a  va 2s . co  m
{ 
public: 
    MyClass(int x = 123, int y = 456) 
    { 
        std::cout << "Default constructor invoked." << '\n'; 
    } 
}; 
int main() 
{ 
    MyClass o; // invoke a default constructor 
} 

If a default constructor is not explicitly defined in the code, the compiler will generate a default constructor.

But when we define a constructor of our own, the one that needs parameters, the default constructor gets removed and is not generated by a compiler.

Constructors are invoked when object initialization takes place.

They can't be invoked directly.




PreviousNext

Related