Search code examples
c++ooppolymorphismrun-time-polymorphism

Runtime polymorphism in C++ using data members


I was studying OOP from here.

It says that runtime polymorphism is possible in C++ using data members.

Now,consider this code:-

#include <iostream>    
using namespace std;    
class Animal {                                 //  base class declaration.  
    public:    
    string color = "Black";      
};     
class Dog: public Animal                       // inheriting Animal class.  
{      
    public:    
    string color = "Grey";      
};    
int main(void) {    
     Animal d= Dog(); 
     Animal d1 = Animal();     
     cout<<d.color<<endl;
     cout<<d1.color<<endl;    
}    

In both the cases above the color "black" is printed. So, how is this example of runtime polymorphism ?


Solution

  • If this was runtime polymorphism you could write a function:

    void foo(Animal& a) {
        std::cout << a.color << "\n";
    }
    

    And it would print the respective color of the object based on the dynamic type of the parameter. However, there is no such thing as "Runtime-polymorphism based on member variables" in C++. The tutorial is wrong and misleading.

    If compile and execute this:

    #include <iostream>    
    using namespace std;    
    class Animal {                                          //  base class declaration.  
        public:    
        string color = "Black"; 
    };     
    class Dog: public Animal                       // inheriting Animal class.  
    {      
        public:    
        string color = "Grey";      
    
    }; 
    
    void foo(Animal& a) {
        std::cout << a.color << "\n";
    }
    int main(void) {    
         Dog d= Dog(); 
         Animal d1 = Animal();     
         foo(d);
         foo(d1);
    } 
    

    The output will be

    Black
    Black
    

    There is no such thing as virtual member variables. Only for virtual member functions use virtual dispatch:

    #include <iostream>    
    using namespace std;    
    class Animal {                                          //  base class declaration.  
        public:    
        virtual std::string color() const { return "Black"; }
    };     
    class Dog: public Animal                       // inheriting Animal class.  
    {      
        public:    
        std::string color() const override { return "Grey"; }
    
    }; 
    
    void foo(Animal& a) {
        std::cout << a.color() << "\n";
    }
    int main(void) {    
         Dog d= Dog(); 
         Animal d1 = Animal();     
         foo(d);
         foo(d1);
    }  
    

    Output:

    Grey
    Black
    

    The turial is wrong and misleading when it says that there would be runtime polymorphis with member variables. Moreover the example they present has object slicing. See here: What is object slicing?.