I have a base class with a number of inherited derived classes. Something like this:
class A {
public:
virtual void f(string foo = "bar") {
cout << foo << endl;
}
};
class B: public A {
public:
void f(string foo = "howdy") {
cout << foo << endl;
}
};
class C: public A {
public:
void f(string foo = "something") {
cout << foo << endl;
}
};
I inherited just two classes for brevity.
This is the main:
A* aArray[] = {
new B,
new C,
};
int main() {
aArray[0]->f();
aArray[0]->f();
return 0;
}
When I run the program, the output that I get back is:
bar
bar
Just like how if the compiler ignores the default arguments of the overridden functions.
Is this normal, or there is something that I'm doing wrong or that I'm missing?
The word “polymorphism” means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics.
Polymorphism is one of the core concepts of object-oriented programming (OOP) and describes situations in which something occurs in several different forms. In computer science, it describes the concept that you can access objects of different types through the same interface.
Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.
Polymorphism is a feature of object-oriented programming languages that allows a specific routine to use variables of different types at different times. Polymorphism in programming gives a program the ability to redefine methods for derived classes.
Default values are statically binded. In other words, they do not have polymorphhic behavior. That's why you saw
bar
bar
instead of those default values in the derived classes' virtual functions.
According to Effective C+:
If default parameter values were dynamically bound, compilers would have to come up with a way to determine the appropriate default values for parameters of virtual functions at runtime, which would be slower and more complicated than the current mechanism of determining them during compilation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With