liuyang wrote: |
---|
If you are talking about the inheritance, the pointer of a derived class instance is the base class pointer itself. |
Hi,
I think that statement is misleading - maybe you wrote it too quickly? Maybe you meant to say that a pointer to Derived is a valid pointer to Base? I am guessing you know all this already - so the stuff that follows is for the benefit of the OP. Also you might be quite right in seeing what the OP is trying to do, which is pretty good work considering the poorly expressed question from the OP.
@Vivienne
If one declares a function to take a pointer to a Base class as an parameter, then the function is called with an argument that is a pointer to an instance of a Derived class object,
then all that happens is the compiler checks to see if Derived really is derived from the Base class. There is no conversion of the pointer to a Base pointer, the pointer is still a pointer to Derived.
One often wouldn't want it to be a pointer to Base anyway, for 2 reasons: The Base is often abstract - so that won't work; It's the pointer to Derived that one wants, so that one can call the Derived class function.
The beauty of this is that it can save one from writing lots of functions, just have class which has a virtual function which takes pointers to Base, then redefine that function in a derived class where necessary to achieve some specialisation.
For example one could have a Base class named
Animal
and it would have a pure virtual function named
Speak();
Then there could be derived classes named Dog, Cow, Duck - each of which redefines the
Speak()
function to
std::cout
the sound that each respective animal makes.
Now create a
std::vector
of pointers to
Animal
. Then
push_back
pointers to the different types of Derived animals. Then cycle through the vector, calling the Speak function for each item in the vector :
item->Speak();
So the advantages here are:
We have one vector of Animals, not a different one for each different type of Animal. This allows us to add more types later on.
We have one
Speak()
function, not
DogSpeak()
,
CowSpeak()
,
DuckSpeak()
. Again this allows us to add more types later on.
So is something like the example above what you are trying to do?