What is constructor in c++

Page Content

The constructor is a special type of member function used to initialize the Object data members with a specific value at the time of its creation and constructor can also be used to allocate the memory.A constructor can be overloaded too.



Characteristics of a constructor


  1. A constructor name must be the same as that of its class name.
  2. It is declared with no return type ( note even void ).
  3. It is declared in public section of the class.
  4. It is automatically invoked when an object is created.
  5. It can have default arguments.
  6. It cannot be declared const but a constructor can be invoked for const objects.
  7. It cannot refer to its own address.
  8. It may not be static.
  9. It may not be virtual.
  10. It can not be inherited.


Type Of Constructor

  1. Default Constructor.
  2. Parameterized Constructor.
  3. Copy Constructor


Default constructor in c++

In C++, a default constructor is a constructor that can be called without any arguments. If a class does not explicitly define any constructors, the compiler provides a default constructor automatically. The default constructor initializes the object's data members to default values or leaves them uninitialized if no initialization is specified.

The syntax for declaring a default constructor in c++

class ClassName {
public:
    // Default constructor declaration
    ClassName()
    {
    
    }
};


The example for a default constructor in c++

#include<iostream>
using namespace std;

class student
{
private:
	int roll;
	int marks;

public:
	student()
	{
		roll = 1001;
		marks = 90;
	}
	void display()
	{
	cout<< "Roll Number is :\t" <<roll << endl;
	cout<< "Marks is :      \t" <<marks << endl;
	}
};

int main()
{
	student s;
	s.display();
}
Output:
Roll Number is :        1001
Marks is :              90




Example:1
Write a program for unparameterized constructor?
#include<iostream>
#include<string.h>
using namespace std;
        
class Student
{
//scope is private, roll and marks are member variables
private : 
int roll;
char name[30];
int marks;
         
public :
Student()  // Unparameterized construcotor
{
roll=1;
strcpy(name,"MR");
marks =100;
}
                       
void display()
{	
cout<<"Roll Number is :"<<roll<<endl;
cout<<"Name is :"<<name<<endl;
cout<<"Marks is :"<<marks<<endl;
}
};
         
int main()
{
Student s; // Object Creation with unparameterized constructor
s.display();
}
Output:
Roll Number is :1
Name is :MR
Marks is :100
            
--------------------------------
Process exited after 0.08815 seconds with return value 0
Press any key to continue . . .
Example:2
Write a program for Parameterized constructor?

Parameterized Constructor
The Constructors with arguments are know as parameterized constructor.
It is used to provide the specific values to the objects
Example :
class sample
{
int a,b;
public :
sample (int x, int y)
{
a=x;
b=y
; }
};
Two ways of passing initial values in arguments to the constructor.
1. Explicit call to constructor:
class_name object_name = function_name(arguments);
sample obj1 = sample(2,9);
2. Implicit call to constructor:
class_name object_name(arguments);
sample obj1(2,3);
#include<iostream>
#include<string.h>
using namespace std;
                   
class Student
{
private : 
int roll;
char name[30];
int marks;
                
public :
// Parameterized construcotor
Student(int r,char n[], int m) 
{
roll=r;
strcpy(name,n);
marks =m;
}
                         
void display()
{
cout<<"Roll Number is :"<<roll<<endl;
cout<<"Name is :"<<name<<endl;
cout<<"Marks is :"<<marks<<endl;
}
};
                
int main()
{
// Object Creation with parameterized constructoer
Student s(101,"Ram",98);
s.display();
}

   
Output:
Roll Number is :101
Name is :Ram
Marks is :98
        
--------------------------------
Process exited after 0.1162 seconds with return value 0
Press any key to continue . . .
Write a program for Default constructor?
Without constructor we can not create any Object so The compiler automatically provide a default constructor with the some dummy values. [default values]
Example:3
#include<iostream>
#include<string.h>
using namespace std;
            
class Student
{
 private : 
 int roll;
 char name[30];
 int marks;
                      
public:
void display()
{
cout<<"Roll Number is :"<<roll<<endl;
cout<<"Name is :"<<name<<endl;
cout<<"Marks is :"<<marks<<endl;
}
};
             
main()
{
Student s; // Object Creation 
s.display();
                    
Student *s1= new Student();// Dynamic type object creation
s1->display();
}
Output:
Roll Number is :1
Name is :
Marks is :0
Roll Number is :0
Name is :
Marks is :0
          
--------------------------------
Process exited after 0.1099 seconds with return value 0
Press any key to continue . . .
Example:4
Write a program to Assign values member variables at declaration?

Execute with warning : non-static data member initializers only available with -std=c++11 or -std=gnu++11
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
private : 
int roll=101;
char name[30]={'A','n','i','l','\0'}; //accepted
//char name[30]="String"; //accepted
int marks=90;
                  
public:
void display()
{
cout<<"Roll Number is :"<<roll<<endl;
cout<<"Name is :"<<name<<endl;
cout<<"Marks is :"<<marks<<endl;
}
};
     
int main()
{
Student s; // Object Creation with unparameterized constructoer
s.display();
                
Student *s1= new Student();// Dynamic type object creation
s1->display();
}
Output:
Roll Number is :101
Name is :Anil
Marks is :90
Roll Number is :101
Name is :Anil
Marks is :90
              
--------------------------------
Process exited after 0.1941 seconds with return value 0
Press any key to continue . . .
Example:5
We can declare member function as static with const keyword only at declaration time.

#include<iostream>
#include<string.h>
using namespace std;
            
class Student
{
               
private : 
//static int roll=101; //Error because without const
static const int roll=101; //acceptable
char name[30]="String";
int marks=90;
                      
public:
void display()
{
cout<<"Roll Number is :"<< roll <<endl;
cout<<"Name is :"<<name<<endl;
cout<<"Marks is :"<<marks<<endl;
}
};
         
int main()
{
Student s; // Object Creation with unparameterized constructoer
s.display();
                        
Student *s1= new Student();// Dynamic type object creation
s1->display();
}
Output:
Roll Number is :101
Name is :String
Marks is :90
Roll Number is :101
Name is :String
Marks is :90
              
--------------------------------
Process exited after 0.2017 seconds with return value 0
Press any key to continue . . .
Copy Constructor
The initialization of an object when done by another object is called Copy Constructor. sample obj1;
sample obj2 (obj1);
we can also write the second statement as
sample obj2 = obj1;
The copy constructor is defined in the class as a parameterized constructor receiving an object as argument passed-by-reference as given below:
class sample
{
..........
..........
public:
sample (sample& obj);//copy constructor
...
};
Example:6

#include<iostream>
using namespace std;
class Code{
int a,b;
public :
Code() // unparameterizde Constructor
{
a = 10;
b = 20;
}
Code(Code& i);// Copy Constructor declared
void display(void)
{
cout<<"a = "<<a<<" b ="<<b<<"\n";
}
};
       
Code :: Code(Code& i) // copy Constructor defined
{
a = i.a;
b = i.b;
}
       
int  main()
{
Code c1,c2(c1); // Copy constructor calling
cout<<endl<<"First object"<<endl;
c1.display();
cout<<endl<<"Second object "<<endl;
c2.display();
cout<<endl<<"Third Object :"<<endl;
Code c3 =c2; // Another way to call the copy constructor
c3.display();
}
Output:
First object
a = 10 b =20
          
Second object
a = 10 b =20
      
Third Object :
a = 10 b =20
          
--------------------------------
Process exited after 0.1845 seconds with return value 0
Press any key to continue . . .
Example:7
Multiple Constructor OR Constructor Overloading
When we have more than one constructor with in the same class is called Constructor Overloading.

#include<iostream>
using namespace std;
class Code
{
int a,b,c;
public :
Code() // unparametrized constructor
{
a=0;
b=0;
c=0;
}
Code(int i, int j); // parameterized constructor
Code(int i, int j, int k)
{
a =i;
b =j;
c =k;
}
void display(void);
};
       
Code :: Code(int i, int j) //constructor definition
{
a =i;
b =j;
}
       
void Code :: display()
{
 cout<<"a= "<<a<<" b="<<b<<" c="<<c<<'\n';
}
       
int main()
{
Code a=Code();// Unparametrized Constructor Calling
a.display();
Code c(5,10); // Two Parameterized Calling
c.display();
Code d=Code(3,9,4); // Three Parameterized Calling
d.display();
}
Output:
a= 0 b=0 c=0
a= 5 b=10 c=21
a= 3 b=9 c=4
          
--------------------------------
Process exited after 0.1692 seconds with return value 0
Press any key to continue . . .
Example:8
Dynamic Construction
Allocation of memory to objects at the time of their construction is known as Dynamic construction of objects.
The constructors, with the use of new operators, can be used to allocate memory while creating objects.
#include<iostream>
#include<string.h>
using namespace std;
class DC   //DC -> Dynamic Constructor
{
char *str;
int length;
public :
DC (char *s)
{
length =strlen(s);
str = new char[length+1]; //get memory
strcpy(str,s);// copy argument to it
}
        
void display()
{
cout<<"String = "<<str<<endl;
}
};
        
int main()
{
DC name1 = "Dynamic Constructors";// Excepted
DC name2 ("Dynamic Constructors");// Excepted
name1.display();
name2.display();
}
Output:
String = Dynamic Constructors
String = Dynamic Constructors
      
 --------------------------------
Process exited after 0.1861 seconds with return value 0
Press any key to continue . . .


Program which will count total number of object is created for a specific class.

#include <iostream>

class MyClass {
public:
    static int count; // Declaration of static data member

    MyClass() {
        count++; // Increment count each time an object is created
    }

    ~MyClass() {
        count--; // Decrement count each time an object is destroyed
    }
};

int MyClass::count = 0; // Definition of static data member

int main() {
    // Create objects
    MyClass obj1;
    MyClass obj2;
    MyClass obj3;

    std::cout << "Number of objects created: " << MyClass::count << std::endl;

    // Create more objects
    MyClass obj4;
    MyClass obj5;

    std::cout << "Number of objects created: " << MyClass::count << std::endl;

    return 0;
}

Example:9
Destructo
A destructor as the name implies is used to destroy the object that has been created by a constructor.
So Destructors are member functions that are used to destroy the objects created by constructors.
Destructors again have the same name as does the class and a tilde sign (~) proceed their name.

The Destructor for the class sample can be defined as :
~ sample(){};

Characteristics of a Destructor:
  1. A destructor has the same name as that of class prefixed by tilde character '~'.
  2. No arguments can be provided to a destructor.
  3. It has not return type, not even void type.
  4. Destructors can't be Inherited
  5. Destructors can't be overloaded
  6. Destructor functions are invoked automatically when the object is destroyed.
  7. If there is no destructor in a class, a default destructor is generated by the compiler.
#include<iostream> 
using namespace std;
class Destructor
{
int a,b;
public:
Destructor(int i, int j);
void display(void);
Destructor();
~Destructor();
          
//   ~Destructor()
//    {
//      cout<<"\n Destructor Called";
//    }
          
};
Destructor :: Destructor()
{
cout<<"Constructor."<<endl;
}
           
Destructor :: Destructor(int i, int j)
{
a=i;
b=j;
}
          
void Destructor :: display()
{
cout<<a<<"\t"<<b<<endl;
}
          
Destructor :: ~Destructor()
{
cout<<"\nDestructor Called"<<endl;
}
          
int main()
{
Destructor();
Destructor c(5,10);
c.display();
}
        
Output:
Constructor.
Destructor Called
5       10
          
Destructor Called
          
--------------------------------
Process exited after 0.1698 seconds with return value 0
Press any key to continue . . .
Example 10
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "Constructor called"<<endl;
}
                
~A()
{
cout << "Destructor called"<<endl;
}
            
};
                
int main()
{
A obj1;   // Constructor Called
int x=1;
if(x)
{
A obj2;  // Constructor Called
}   // Destructor Called for obj2
}
Output
Constructor called
Constructor called
Destructor called
Destructor called

--------------------------------
Process exited after 0.1736 seconds with return value 0
Press any key to continue . . .