Home C++ Tutorial Constructor

Constructor

by Adarsh Pal
35 minutes read

A function is called whenever we create an object this function is called a Constructor or we can say a Constructor invoked during object creation, it has no return type and no input parameter; Constructor has a name similar to the Class Name.

#include<iostream>
using namespace std;
class Animal{
   public:
   char rank;
   //Constructor
   Animal(){
   cout<<"constructor Is Called"<<endl;
   }
};
int main(){
   Animal Dog;
   Dog.rank='X';
   cout<<Dog.rank<<endl;
}
 //output:constructor Is Called
  //        X

In the above code before printing the rank of the Dog the Constructor will be called during the object creation, if we will not define a constructor then there will be a default constructor i.e Dog.Animal( )

Parameterized Constructor

In parameterized Constructor we can pass an Argument during object creation, given below is a demonstration about how a Parameterized Constructor can be Implemented.

#include<iostream>
using namespace std;
class Score{
     private:
     int x1,x2;
     public:
     //Parameterized Constructor
     Score(int x, int y){
       x1=x;
       x2=y;
     }
     //getter
     int getX1(){
     return x1;
     }
     int getX2(){
     return x2;
     }
};
int main(){
 Score S1(2,3);
 cout<<"Score of X1 : "<<S1.getX1()<<endl;
 cout<<"Score of X2 : "<<S1.getX2()<<endl;
}

Copy Constructor

Copy Constructor is used to initialize the members of a newly created object by copying the already existing object, given below is a demonstration about how a Parameterized Constructor can be Implemented.

#include<iostream>
using namespace std;
class Score{
     private:
     int x1,x2;
     public:
     //Parameterized Constructor
     Score(int x, int y){
       x1=x;
       x2=y;
     }
     //getter
     int getX1(){
     return x1;
     }
     int getX2(){
     return x2;
     }
};
int main(){
 Score S1(2,3);
 //Copy Constructor called
 Score S2(S1);
 cout<<"Score of X1 : "<<S2.getX1()<<endl;
 cout<<"Score of X2 : "<<S2.getX2()<<endl;
}

related posts

Leave a Comment