Write a program that demonstrate the use of constructor with default
arguments for the following problem. Define a class Person with data member as name
and age. Create three objects with no argument, one argument name and two argument
name and age. You are not allowed to create more than one constructor.
#include <iostream>
using namespace std;
class Person
{
string _name;
int _age;
public:
Person()
{
_name = "";
_age = 0;
}
Person(string name, int age = 20)
{
_name = name;
_age = age;
}
string GetName()
{
return _name;
}
int GetAge()
{
return _age;
}
};
int main()
{
Person defaultConstructor;
Person defaultAge("Jim");
Person initializedConstructor("Andrew", 25);
cout << "Info about person created with default constructor: name = " << defaultConstructor.GetName() << ", age = " << defaultConstructor.GetAge() << endl;
cout << "Info about person created with default age: name = " << defaultAge.GetName() << ", age = " << defaultAge.GetAge() << endl;
cout << "Info about person created with initialized constructor: name = " << initializedConstructor.GetName() << ", age = " << initializedConstructor.GetAge() << endl;
return 0;
}
Comments
Leave a comment