How to set default parameters In case a user does not type in the other one

Viewed 61
#include <iostream>

class Person {
    friend std::ostream &operator<<(std::ostream &os, const Person &person);
    std::string name;
    int age;
public:
    std::string get_name () {return name;}
    int get_age() {return age;}
    Person() : name{"Unknown"}, age{0} {}
    Person(std::string name, int age) : name{name}, age{age} {}
};

std::ostream &operator<<(std::ostream &os, const Person &person) {
    os << person.name << ": " << person.age;
    return os;
}

int main () {
    Person Austin{"Austin", 12}; 
}

I am trying to have it where for my name I type in "Austin", but If I don't type in age it will automatically make it a 0 because I did not enter a age.

2 Answers

Since C++11 you can take advantage of delegating constructors: you can provide an additional constructor overload that takes only an std::string for the name and delegates to the existing constructor that accepts the two arguments, std::string and int. Then, just pass 0 as the second argument to the delegated constructor:

Person(std::string name) : Person(name, 0) {}

That is, Person(std::string) would be the delegating constructor, and the existing Person(std::string, int) the delegated one.


Another approach would be to use a default argument for the second parameter of the existing constructor that accepts both an std::string and an int:

Person(std::string name, int age = 0) : name{name}, age{age} {}

The drawback to this latter approach is that the default argument is always compiled directly in client code. This would make recompiling the client code necessary whenever a default argument changes.

C++ has default parameters, use them.

Person(std::string name, int age=0) : name{name}, age{age} {}

Does exactly what you asked for

int main () {
    Person Austin{"Austin"}; 
    std::cout << Austin << std::endl; //prints out "Austin: 0"
}
Related