When derived is cast back into base. By safe, I mean it works properly for known c++ compiler. It seems to be working for VIsual C++ 2008. E.g
class zero
{
virtual int v()=0;
}
class a: public zero
{
public:
int value;
a(int vin)
{
value =vin;
}
int v()开发者_StackOverflow
{
return value;
}
}
zero *e1= new a(3);
cout << e1->v();
It is safe and fully correct behaviour. That is the reason why you have virtual or pure virtual methods. Most of the time you will want to hide implementation details and manipulate objects through their interface (or pure virtual class). That is standard and all C++ compilers must support it.
Yes, it is safe. That's the whole point of virtual functions, they are called on the actual type of an object, not the declared type.
It is safe but you should consider providing either a public virtual destructor in zero or a non-virtual protected destructor depending on whether you want to be able to delete objects derived from zero through the base pointer.
Not only is it safe but this is one of the main reasons for inheritance and polymorphism: your zero class provides an interface that is applicable to any type that implements it, regardless of what additional data they store and what additional functionality they provide. Through this shared interface, this multitude of types implementing zero can all be accessed and stored through this common interface that describes the shared aspects of all of them. This is the essence of polymorphism (both static and dynamic) and a very useful means of cutting down redundant code working across related types.
精彩评论