Constructor Overloading
Constructor can be overloaded in similar way as function overloading. Overloaded constructors have same name (name of the class) but different number of argument passed. Depending upon the number and type of argument passed, specific constructor is called. Since, constructors are called when object is created. Argument to the constructor also should be passed while creating object. Here is the modification of above program to demonstrate the working of overloaded constructors.
/* Source Code to demonstrate the working of overloaded constructors */
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
Area( ): length(5), breadth(2){ } // Constructor without no argument
Area(int l, int b): length(l), breadth(b){ } // Constructor with two argument
void GetLength( )
{
cout<<"Enter length and breadth respectively: ";
cin>>length>>breadth;
}
int AreaCalculation( ) { return (length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp<<endl;
}
};
int main( )
{
Area A1, A2(2,1);
int temp;
cout<<"Default Area when no argument is passed."<<endl;
temp=A1.AreaCalculation( );
A1.DisplayArea(temp);
cout<<"Area when (2,1) is passed as argument."<<endl;
temp=A2.AreaCalculation( );
A2.DisplayArea(temp);
return 0;
}
Explanation of Overloaded Constructors: For object A1, no argument is passed. Thus, the constructor with no argument is invoked which initializes length to 5 and breadth to 2. Hence, the area of object A1 will be 10. For object A2, 2 and 1 is passed as argument. Thus, the constructor with two argument is called which initializes length to l(2 in this case) and breadth to b(1 in this case.). Hence the area of object A2 will be 2.
Output
Default Area when no argument is passed.
Area: 10
Area when (2, 1) is passed as argument.
Area: 2
Default Copy Constructor
An object can be initialized with another object of same type. Let us suppose the above program. If you want to initialize an object A3 so that it contains same value as A2. Then, this can be performed as:
....
int main()
Default Copy Constructor
An object can be initialized with another object of same type. Let us suppose the above program. If you want to initialize an object A3 so that it contains same value as A2. Then, this can be performed as:
....
int main()
{
Area A1, A2(2,1);
Area A3(A2); /* Copies the content of A2 to A3 */
OR,
Area A3=A2; /* Copies the content of A2 to A3 */
}
You might think you may need some constructor to perform this task. But, no additional constructor is needed. It is because this constructor is already built into all classes.
No comments:
Post a Comment