Can I get polymorphic behavior without using virtual functions?

后端 未结 11 1390
栀梦
栀梦 2020-12-03 13:54

Because of my device I can\'t use virtual functions. Suppose I have:

class Base
{
    void doSomething() { }
};

class Derived : public Base
{
    void doSom         


        
11条回答
  •  被撕碎了的回忆
    2020-12-03 14:23

    Small program for understanding, we can use static_cast for down casting the base class pointer to the derived class and call the function.

    #include
    
    using namespace std;
    
     class Base
    {
      public:
    
       void display()
        {
          cout<<"From Base class\n";
        }
     };
    
     class Derived:public Base
     {
       public:
    
        void display()
        {
          cout<<"From Derived class";
    
        }
       };
    
    int main()
    {
      Base *ptr=new Derived;
      Derived* d = static_cast(ptr);
      ptr->display();
      d->display();
      return 0;
    }
    

    Output:

    From Base class From Derived class

提交回复
热议问题