views:

190

answers:

5

Hi,

i'm slightly confused about this run time polymorphism. correct me if i am wrong, run time polymorphism means, function definitions will get resolved at run time.

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, base class knows that its pointing to derived class b. so where does the ambiguity exist? in what cases we call, the function definitions will get resolved at run time.?

+9  A: 

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;
}
anon
A: 

You need to have some useful business method declared in the base and in each derived class. Then you have code such as

 a->someMethod();

Now the a pointer might point to an instance of any of the derived classes, and so the type of what a is pointing to must determine which someMethod() is called.

djna
A: 
DumbCoder
+1  A: 

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

liaK
A: 

Runtime means that exact method will be known only at run time. Consider this example:


class BaseClass
{
public:
  virtual void method() {...};
};

class DerivedClassA : public BaseClass
{
  virtual void method() {...};
};

class DerivedClassB : public BaseClass
{
  virtual void method() {...};
};

void func(BaseClass* a)
{
  a->method();
}

When you implement your ::func() you don't know exactly type of instance pointed by BaseClass* a. It might be DerivedClassA or DerivedClassB instance etc.
You should realize, that runtime polymorphism requires special support from language (and maybe some overhead for calling "virtual" functions). In C++ you "request" for dynamic polymorphism by declaring methods of base class "virtual" and using public inheritance.

vnm