How does inheritance work in this snippet of code?

Viewed 48

I am learning about inheritance and I am a bit confused by one of the problems I got. In this problem, why is the output The color is orange and not The color is orangeThecolor is red?

using namespace std;

class Red{
    public: void print(){
        cout<<"The color is red";
    }
};

class Orange: public Red{
    public: void print(){
        cout<<"The color is orange";
    }
};

class Yellow: public Orange{};

int main()
{
    Orange colorOrange;
    colorOrange.print();
    
    return 0;
}
1 Answers

why is the output "The color is orange" and not "The color is orangeThecolor is red"?

Because when you wrote colorOrange.print(); lookup starts from the derived class and then it finds the Yellow::print() and so the search stops and this already found print is called/used. Thus you get the output The color is orange and nothing more.

In other words, the print inside the derived class hides the version from the base class.

If you want to call the Red::print() in addition to the Yellow::print() then you could add a call to base' print version by adding Red::print() as shown below:

class Orange: public Red{
    public: void print(){
        cout<<"The color is orange";
        //added this to call Red::print() 
        Red::print();
    }
};

Demo

Related