tags:

views:

135

answers:

3

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()
   {
      return value;
   }
}


zero *e1= new a(3);
cout << e1->v();
+14  A: 

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.

jdehaan
+1 Simple and straight to the point answer
Iulian Şerbănoiu
using it as a interface, that is clear. I was not clear about what happens to the variables defined in a derived class. Look like they are kept somehow.
Aftershock
@Aftershock Notice that the type of e1 is pointer to a zero. Notice that what it points to is (from the moment it is created until it is destroyed) of type a. The type of the pointer does _not_ alter the type of what it points to, because objects never change type once created. The original example you gave is just a textbook example of polymorphism (good keyword to google for more relevant info).
apollodude217
What @jdehaan said applies to most OO languages you will encounter, as well.
apollodude217
+4  A: 

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.

Donnie
+1  A: 

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.