Assume there are class A , and class B that inherits A. what is the correct way to use B objects?
I’ve seen in “cplusplus.com” that they are “using” B objects this way:
B b;
A* a=&b;
What’s the difference between using a class “A” pointer and using b?
Thanks!
The advantage of using pointers to base classes comes when you have virtual functions.
Imagine the following
now if we have a pointer to base class we can call
func()on it and the correct function is called depending on whether the pointer actually points at anA, aBor aC. Example:will output the following
Now you may say why not use three different pointers to A, B and C types separately but what if you wanted an array of pointers? Then they would all need to be the same type, namely
A*. This type of polymorphism is useful for grouping things which are similar in function or spirit but different in implementation.