Discuss constructors with default arguments and constructor overloading with the help of suitable
examples.
#include<iostream>
using namespace std;
/*In C++, We can have more than one constructor in a class with same name,
as long as each has a different list of arguments.This concept is known as
Constructor Overloading and is quite similar to function overloading.
- Overloaded constructors essentially have the same name (exact name of the
class) and differ by number and type of arguments.
- A constructor is called depending upon the number and type of arguments passed.
- While creating the object, arguments must be passed to let compiler know,
which constructor needs to be called. */
class Person
{
int age;
public:
//1 - Constructor with no arguments
Person():age(18){}
//2 - Parametrized constructor
Person(int _age) :age(_age) {}
void Display() { cout <<"Person "<< age<<endl; }
};
\\
class Person2
{
int age;
public:
//1 - Constructor with with default value argument
//can replace two constructors from the class Person
Person2(int _age=18) :age(_age) {}
void Display() { cout << "Person2 " << age<<endl; }
};
int main()
{
//Default constructor
Person a;
a.Display();
//Parametrized constructor
Person b(55);
b.Display();
//Constructor with with default value argument
Person2 c;
c.Display();
Person2 d(55);
d.Display();
}
Comments
Leave a comment