Question:
difference between inheritance and polymorphism?
kamasymo
2006-04-14 15:19:13 UTC
difference between inheritance and polymorphism?
Four answers:
2006-04-14 15:25:10 UTC
Inheritance is the ability of a variable / object to have a "default" value based on being spawned from another variable / object.



Polymorphism is the ability of a variable to change types based on having its value reassigned.



For example, in HTML, if you don't set the style of the

tag, that tag will use whatever the user's Web browser has set for a default font face and size. That's inheritance.



Also, if in PHP, I set the following:



$x = "hello world";

$x = 5;



I have demonstrated polymorphism; $x was first a string, now it's an integer.

?
2017-01-12 20:34:14 UTC
Difference Between Inheritance And Polymorphism
horus
2006-04-14 19:20:25 UTC
Polymorphism works through inheritance.

In C++ when you derive a class D from a base class B the class D will have all the attributes and behavior of class B. This is inheritance i.e. D inherits B.

Inheritance allows you to declare some variable to be of type B* (that is a pointer to an object of type B) then assign an address of an object of type D to this variable.

This goes as follows.

DaDobj;

B*pBobj = &aDobj;

pBobj is a pointer that is supposed to have the address of an object of type B but instead it has the address of an object of type D. This is totally legal as each object of type D is also an object of type B. This have the big advantage of allowing you to put several objects of types B and D in a single collection if you used B* as the type that the collection accepts.

Polymorphism enters the scene after that. It requires inheritance and it also requires virtual member functions. When class B has virtual functions class D will inherit these functions. But class D can provide a different implementation of any of these functions. The problem will be if you have several variables all of type B* you can't tell which points to a B object and which point to a D object so if you call a virtual function f() through the pointer which implementation will be carried out? Polymorphism means that the right implementation will be used. This means that if the pointer points to a B object the implementation in the B class will be used and if it points to a D the implementation in the D class will be used.
at_bhushan
2006-04-14 15:24:54 UTC
Inheritnce is said to be the case when one class inherits the data and functions of another base class

whereas

polymorphism is when the same name behaves differently when accessed through different classes i.e. base or derived class.

for the full theory see any online reference. I will recommend complette reference of C++.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...