0

******************* Here I can use Derive pinter at compile time **************** **** Also run time polymorphism is slower *******************************

    #include <iostream> 
    using namespace std; 
    class base { 
        public: 
        virtual void print() 
        { 
            cout << "print base class" << endl; 
        } 
    
        void show() 
        { 
            cout << "show base class" << endl; 
        } 
    }; 
    class derived : public base { 
    public: 
        void print() 
        { 
            cout << "print derived class" << endl; 
        } 
       void show() 
        { 
            cout << "show derived class" << endl; 
        } 
    }; 
    
int main() 
    { 
        base* bptr; 
        derived d; 
        bptr = &d; 
    
        // virtual function, binded at runtime 
        bptr->print(); 
      //binded at compile time 
        derived *dptr =&d; 
        dptr->print();
    } 
  • 4
    Does this answer your question? [Why use base class pointers for derived classes](https://stackoverflow.com/questions/9425822/why-use-base-class-pointers-for-derived-classes) – Mohit Kumar Aug 23 '20 at 05:50

1 Answers1

0

Here's no difference between using base* or derived* in your code as it's an example that almost does nothing.

In real applications, people use base class pointers to have the flexibility of swapping different derived classes without changing the caller's code. See: polymorphism for more information.

Also see this example:

class Animal {
  virtual void eat() = 0;
}
class Cat : public Animal {
  void eat();
}
class Dog : public Animal {
  void eat();
}
int main() {
  Cat cat;
  Dog dog;
  std::vector<Animal *> animals= {&cat, &dog};
  for (Animal *animal : animals) {
    animal->eat();
  }
}

Here, we rely on the use of the base class pointer (Animal *) to call eat() in different derived classes.

Heron Yang
  • 336
  • 2
  • 16