Answer to Question #326672 in C++ for Abhi

Question #326672

 Discuss constructors with default arguments and constructor overloading with the help of suitable 

examples.


1
Expert's answer
2022-04-10T05:24:42-0400
#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();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS