2.2.4 Example: Splitting a String

So why do we use default values?

Default values help simplify our code so that we donโ€™t need to use multiple function overrides.

We can use one function to handle multiple parameter set ups.

Default values and Function Overload

One place to be cautious is when using default values in a function overload situation. Letโ€™s take a look at an example.

double pow(double base, int exp = 2) {...}
double pow(double base, double exp = 2.0) {...}

Even though the function header is different, if the only difference is in a default value, the compiler will throw an error.

In the example above, because of default values, you could call the method with just one parameter. If you do that, C++ will not know which method to use, so it throws a compiler error.

Splitting a String

Let's walk through an example of how getline can be used to split a string into different pieces. This is a helpful algorithm that you will see again later in the course.

To do this, you will convert a string into an input stream. Just like the cin is an input stream, a string can be used as an input stream and used in the cin command.

Last updated