Professional Documents
Culture Documents
2. Explicit calling
class_name object_name=constructor(actual
arguments);
Overloading Constructors
Similar to the function, it is also possible to
overload the constructors.
A class can contain more than one constructors,
as long as the argument list is different.
This is known as "constructor overloading". All
constructors are defined with same name as the
class name.
Depending upon on the number of arguments the
compiler executes appropriate constructor.
Write a C++ program with multiple constructors for the
single class?
#include<iostream.h>
#include<conio.h>
class cse
{
int b,g;
public:
cse() //constructor
{
b=25;
g=35;
}
cse(int x,int y) //constructor
{
b=x;
g=y;
}
cse(int x) //constructor
{
b=g=x;
}
void display()
{
cout<<"The Boys are:"<<b<<endl;
cout<<"The Girls are:"<<g<<endl;
}
};
int main()
{
cse ca,cb(15,45),cc(30); //calling different constructors
clrscr();
cout<<"------ First Object:-----"<<endl;
ca.display();
cout<<"-------Second Oject:------"<<endl;
cb.display();
cout<<"-------Third Object:------"<<endl;
cc.display();
getch();
return 0;
}
Array of Objects Using Constructors
#include<iostream.h>
#include<conio.h>
#include<math.h>
class power
{
int num,pr,ans;
public:
power(int n=5,int p=3) //default arguments
{
num=n;
pr=p;
ans=pow(num,pr);
}
void display()
{
cout<<num<<" power "<<pr<<" is "<<ans<<endl;
}
};
int main()
{
power p1,p2(2),p3(3,3); //calling constructor
clrscr();
p1.display();
p2.display();
p3.display();
getch();
return 0;
}
Copy Constructors
Characteristics:
› The data members of the const object will be read-only, any effort
to alter the data members will cause to generate an error.
› The data members of the const object are also called "read-only"
data members.
› The const object can access const member functions only.
Calling Constructors and Destructors
You can overload the assignment operator (=) just as you can
other operators and it can be used to create an object just like
the copy constructor.
The assignment operator can be overloaded in two ways:
› Implicit overloading
implic.cpp example program
Syntax: n2=n1;
› Explicit overloading
Explic.cpp
Syntax n2.operator=(n1);
Type Conversion