Answer to Question #181993 in C++ for ayush singh

Question #181993

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.


1
Expert's answer
2021-04-15T14:43:05-0400
#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;
}

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