Kindly explain me the concept of constructor overloading.
Constructor is a special function of class. It is not the same but something similar like function. Constructor is a function which call automatically at the time of execution of program. The name of a constructor is same as the name of the class. Constructor can take parameter also, Constructor containing parameter are called parametrized constructor.
Constructor overloading:
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
int y;
// Overload the default constructor.
MyClass() { x = y = 0; }
// Constructor with one parameter.
MyClass(int i) { x = y = i; }
// Constructor with two parameters.
MyClass(int i, int j) { x = i; y = j; }
};
int main() {
MyClass t; // invoke default constructor
MyClass t1(5); // use MyClass(int)
MyClass t2(9, 10); // use MyClass(int, int)
cout << "t.x: " << t.x << ", t.y: " << t.y << "\n";
cout << "t1.x: " << t1.x << ", t1.y: " << t1.y << "\n";
cout << "t2.x: " << t2.x << ", t2.y: " << t2.y << "\n";
return 0;
}
t.x: 0, t.y: 0
t1.x: 5, t1.y: 5
t2.x: 9, t2.y: 10
Constructor overloading:
#include <iostream>
using namespace std;
class MyClass {
public:
int x;
int y;
// Overload the default constructor.
MyClass() { x = y = 0; }
// Constructor with one parameter.
MyClass(int i) { x = y = i; }
// Constructor with two parameters.
MyClass(int i, int j) { x = i; y = j; }
};
int main() {
MyClass t; // invoke default constructor
MyClass t1(5); // use MyClass(int)
MyClass t2(9, 10); // use MyClass(int, int)
cout << "t.x: " << t.x << ", t.y: " << t.y << "\n";
cout << "t1.x: " << t1.x << ", t1.y: " << t1.y << "\n";
cout << "t2.x: " << t2.x << ", t2.y: " << t2.y << "\n";
return 0;
}
t.x: 0, t.y: 0
t1.x: 5, t1.y: 5
t2.x: 9, t2.y: 10
0 Comments
Please add nice comments or answer ....