What exactly does runtime polymorphism mean?

By : Naruto
Source: Stackoverflow.com
Question!

I'm slightly confused about runtime polymorphism. Correct me if I am wrong, but to my knowledge, runtime polymorphism means that function definitions will get resolved at runtime.

Take this example:

class a
{
a();
~a();
void baseclass();
}

class b: class a
{
b();
~b();
void derivedclass1();
}

class c: class a
{
c();
~c();
void derivedclass2();
}

Calling methodology:

b derived1;
a *baseptr = &derived1; //here base pointer knows that i'm pointing to derived class b. 
baseptr->derivedclass1();

In the above calling methodology, the base class knows that it's pointing to derived class b.

So where does the ambiguity exist?

In what cases will the function definitions get resolved at runtime?

By : Naruto


Answers
There is no ambiguity exists in the example provided.

If the base class has the same function name as the derived class, and if you call in the way you specified, it will call the base class's function instead of the derived class one.

In such cases, you can use the virtual keyword, to ensure that the function gets called from the object that it is currently being pointed. It is resolved during the run time.

Here you can find more explanation..

By : liaK


This code, at run time, calls the correct version of f() depending on the type of object (A or B) that was actually created - no "ambiguity". The type cannot be known at compile-time, because it is selected randomly at run-time.

struct A {
   virtual ~A() {}
   virtual void f() {}
};

struct B : public A {
   virtual void f() {}
};


int main() {
   A * a = 0;
   if ( rand() % 2 ) {
      a = new A;
   }
   else {
      a = new B;
   } 
   a->f();   // calls correct f()
   delete a;
}
By : liaK


Turn this

void baseclass();

to

virtual void baseclass();

Override this in your Derived classes b and c. Then

b *derived1 = new derived1 ();
a *baseptr = derived1; //base pointer pointing to derived class b. 
baseptr->baseclass();

will invoke derived1 definition, expressing run time polymorphism. And do remember about making your destructor virtual in Base. Some basic reading material for polymorphism

By : DumbCoder


This video can help you solving your question :)
By: admin