Can I get polymorphic behavior without using virtual functions?

Viewed 10024

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

class Base
{
    void doSomething() { }
};

class Derived : public Base
{
    void doSomething() { }
};

// in any place
{
    Base *obj = new Derived;
    obj->doSomething();
}

the obj->doSomething() will call just the Base::doSomething()

Is there a way with Base *obj, to call the doSomething of the Derived?

I know I can just put a virtual before doSomething() of Base it solve the problem, but I'm limited by my device, the compiler doesn't support it.

11 Answers

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<iostream>

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<Derived*>(ptr);
  ptr->display();
  d->display();
  return 0;
}

Output:

From Base class From Derived class

Related