Call derived class method from base class reference

前端 未结 2 1800
南旧
南旧 2020-12-31 12:10
class Material
{
public:
 void foo()
 {
  cout << \"Class Material\";
 }
};

class Unusual_Material : public Material
{
public:
 void foo()
 {
  cout <<          


        
相关标签:
2条回答
  • 2020-12-31 12:59

    What you want is polymorphism, and to enable it for a function you need to make it virtual:

    class Material 
    { 
    public: 
        virtual void foo() // Note virtual keyword!
        { 
            cout << "Class Material"; 
        } 
    }; 
    
    class Unusual_Material : public Material 
    { 
    public: 
        void foo() // Will override foo() in the base class
        { 
            cout << "Class Unusual_Material"; 
        } 
    }; 
    

    Also, polymorphism only works for references and pointers:

    int main()  
    {  
        Unusual_Material unusualMaterial;
        Material& strange = unusualMaterial;
        strange.foo();  
        return 0; 
    }
    
    /* OR */
    
    int main()  
    {  
        Unusual_Material unusualMaterial;
        Material* strange = &unusualMaterial;
        strange->foo();  
        return 0; 
    }
    

    What you have in your code snippet will slice the Unusual_Material object:

    int main() 
    { 
        // Unusual_Material object will be sliced!
        Material strange = Unusual_Material(); 
        strange.foo(); 
        return 0; 
    } 
    
    0 讨论(0)
  • 2020-12-31 13:03

    Still better explanation would be..

    class Base
    {
    public:
     void foo()     //make virtual void foo(),have derived method invoked
     {
      cout << "Class Base";
     }
    };
    class Derived: public Base
    {
    public:
     void foo()
     {
      cout << "Class Derived";
     }
    };
    int main()
    {
     Base base1 = Derived ();
     Base1.foo(); //outputs "Class Base" 
               // Base object, calling base method
    
     Base *base2 = new Derived ();
     Base2->foo(); //outputs"Class Base",Again Base object calling base method
    
    // But to have base object, calling Derived method, following are the ways
    // Add virtual access modifier for base foo() method. Then do as below, to //have derived method being invoked.
    //
    // Base *base2 = new Derived ();
    // Base2->foo();    //outputs "Class Derived" .
    
    return 0;
    }
    
    0 讨论(0)
提交回复
热议问题