Call derived class method from base class reference

前端 未结 2 1817
南旧
南旧 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 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;
    }
    

提交回复
热议问题