Default parameters in C++

In C++, you can define a default value for parameter(s) of a function. Here's how you do it:

#include <iostream>
using namespace std;

void show_info(string name = "Pantha", int age = 20) {
 cout << name << " is " << age << " years old." << endl;
}

int main() {
 show_info();
 show_info("Beck");
 show_info("Tony", 22);

 return 0;
}

Here, we have defined a function named show_info which takes two arguments - name and age. We also set a default value for name = "Pantha" (which is of type string) and also, the default value for age = 20. Then we call the function show_info three times - three different ways (in this case). Its as easy as that!
One more thing that you should be aware of is, you cannot change the position of arguments while calling the function. For example, you CANNOT DO the following:

show_info(20, "Andy");

That's all!

No comments:

Post a Comment

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...