Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism & default values: can co-exist? [duplicate]

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?

like image 897
Overflowh Avatar asked May 18 '13 17:05

Overflowh


People also ask

What is polymorphism with example?

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.

What is the concept of polymorphism?

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.

What is meant by polymorphism in Java?

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.

What is polymorphism used for?

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.


1 Answers

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.

like image 109
taocp Avatar answered Oct 06 '22 01:10

taocp