A constructor is a special type of member function that is called automatically when an object is created.
In C++, a constructor has the same name as that of the class and it does not have a return type.
C++ Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of creating object.
Example:-
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:-
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor
A constructor which has parameters is called the parameterized constructor. It is used to provide different values to distinct objects.
Example:-
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:-
101 Sonoo 890000
102 Nakul 59000
Copy Constructor in C++
The copy constructor in C++ is used to copy data of one object to another.
Example:-
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
num1 = n1;
num2 = n2;
}
Demo(const Demo &n) {
num1 = n.num1;
num2 = n.num2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main() {
Demo obj1(10, 20);
Demo obj2 = obj1;
obj1.display();
obj2.display();
return 0;
}
Output:-
num1 = 10
num2 = 20
num1 = 10
num2 = 20
Comments
Post a Comment