1

I know how virtual function is used to achieve RT polymorphism .By using base class reference and storing derived class object in it.And then calling the overridden method using this reference. But Is this also true?

class Base
{
 public:
 void show();
 {
  cout << "Base class\t";
 }
};
class Derived:public Base
{
 public:
 void show()
 {
  cout << "Derived Class";
 }
}

int main()
{
 Base b;       //Base class object
 Derived d;     //Derived class object
 d.show();   // is this run time polymorphism??
}

//Output : Derived class

4
  • It is not (cannot be) run-time polymorphism because the exact method is determined during compilation based only on the type information. There is no run-time dispatch involved. Commented Sep 22, 2015 at 19:41
  • so this is not even method overriding? I got the code from studytonight.com/cpp/function-overriding.php please tell if this example for overriding is wrongly put in the site Commented Sep 22, 2015 at 19:59
  • This is known as Function Hiding. Commented Sep 22, 2015 at 20:05
  • @user2864740 thanks a lot. This cleared my doubt. Commented Sep 22, 2015 at 20:14

1 Answer 1

2

No, it is not. Because this

 Derived d;
 Base *b = &d;
 b->show();

prints

Base class

Whereas with run-time polymorphism it would print

Derived Class

There is no polymorphism in your example because the exact type of the object is known at the calling site. Also you hide the base function, not override nor overload it.

Sign up to request clarification or add additional context in comments.

6 Comments

because for that you have to declare show method in base as virtual.What I am asking here is using derived class obj to call overridden method as RT polymorphism
The code has polymorphism.i think.It is a simple example of function overridding. And function overriding is considered as Polymorphism right
@SaurabhKumar: no, it is not overriding.
@SaurabhKumar: polymorphism is the scenario when the code can do different things depending on the exact type of the object which is not known at that point in code. Static polymorphism is when the type is determined at the time of template instantiation, dynamic is when it is determined at runtime through the vtable. It has nothing to do with overriding.
May be you both are right.I read the code from this site: studytonight.com/cpp/function-overriding.php Please tell me if the information in the site is wrong
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.