Hi, Im relatively new to C++, and in the book im currently reading, came across the topic of Polymorphism. Just wanted to ask a couple of questions:

1) Base* ptr = new sub;
Kinda confused about this - and also, how/why it is useful to have a base class pointer storing the adress of a sub class. Perhaps someone could clear this up for me? :)

2) Virtual functions/methods
Why/how are these useful?

- Shift_ -

i dont know the answer of ur 1st question....yes but i can somewhat help u with the second one....
take the case of dreaded diamond(combination of multiple and hierarchial inheritance)
u will see that the data members and member functions get inherited to bothe the derived class from the base class...and when the turn comes for the data members and memberfunctions of these 2 class to be inherited by the next derived class...u will see that there will be 2 copies of the D.M and M.F(data members and member func)....
to avoid these u inherit the M.F and D.M from the first base class to the intermediate 2 derived class by giving the code
class classname:virtual public/private/protected....
so as to avoid multiple copies of the same D.M and M.F in the most derived class....:):)

1) Base* ptr = new sub;
Kinda confused about this - and also, how/why it is useful to have a base class pointer storing the adress of a sub class. Perhaps someone could clear this up for me?

Generally, it's useful when you want to handle multiple related types (which all have the same interface) without duplicating a lot of code to do so.

2) Virtual functions/methods
Why/how are these useful?

Virtual member functions are the feature that allows polymorphism.

i dont know the answer of ur 1st question....yes but i can somewhat help u with the second one....
take the case of dreaded diamond(combination of multiple and hierarchial inheritance)
u will see that the data members and member functions get inherited to bothe the derived class from the base class...and when the turn comes for the data members and memberfunctions of these 2 class to be inherited by the next derived class...u will see that there will be 2 copies of the D.M and M.F(data members and member func)....
to avoid these u inherit the M.F and D.M from the first base class to the intermediate 2 derived class by giving the code
class classname:virtual public/private/protected....
so as to avoid multiple copies of the same D.M and M.F in the most derived class....

That's virtual inheritance, not virtual functions.

This article has been dead for over six months. Start a new discussion instead.