When to used derived class pointer and base class pointer
Can anyone help me, when i have to used base class and dervied class pointe开发者_如何学编程r.
It depends on why you're deriving. If it is for an OO implementation,
most of the time, you'll use pointers to the base class (which will
often by abstract) exclusively; you'll only use pointers to the derived
class if the derived class defines an extended interface. But
inheritance in C++ is a technique, and it is often used for other
purposes. (Think of an iterator class, which inherits from an
instantiation of std::iterator
. This is not OO derivation, and
you'ld never use a pointer the the instance of std::iterator
.)
I'll often make the distinction, using "derivation" for the OO concept, and "inheritance" for the C++ technique. But this is in no way standard, and terminology varies greatly, so you'll usually have to start by figuring out what the author is talking about: OO design or C++ implementation. And you'll sometimes end up realizing that he doesn't know himself; that he's confusing the two in his own mind. Inheritance is the C++ language construct used to implement OO derivation, but this language construct can be used for other things.
When you have more than one derived classes. and you don't know at compile time that which derived class will be instantiated at runtime. base class pointer is preferred over derived class pointer.
Use the derived class pointer when you want to use the derived class interface, or when you want to ensure that you're dealing with this particular implementation of the base class, or when you want to call a non-virtual function defined in the derived class.
In other circumstances, it doesn't matter.
Base class pointers are used when you have multiple derived classes but you want to abstract yourself from the derived class type. This can be very useful for example in situations like this:
class Animal {
Animal();
}
class Dog : public Animal {
Dog();
}
class Cat : public Animal {
Cat();
}
As you see, in this example you have a base class (Animal) and two derived classes (Cat and Dog). Lets say now that you're running a zoo (that only has Cats and Dogs :) ), and you need to keep up a list of your animals. You could just create two separate lists, one for Cats and another for Dogs. However, if you consider that Cats and Dogs are just Animals, you could create a list with pointers to Animals.
This way, by abstracting yourself from the derived class type, you can work with different derived classes by having a simple pointer to a base class.
Derived class pointers are completely different since they can only "represent" the derived class type.
精彩评论