Is the second case OK?
Or is there any other way i can perform this cast, if i want
a derived type instance, and the reference to the base is not created by the new operator?
#include <iostream>
#include <stdio.h>
usingnamespace std;
class Base {
public:
int value1;
// default constructor:
Base () {
value1 = 0;
}
// notice:to perform a dynamic cast on a type, the type
// MUST HAVE AT LEAST ONE VIRTUAL MEMBER
// if the following method is commented out,we will get
// a compilation error caused by dynamic_cast in main();
virtualvoid setValue(int newValue) {
value1 = newValue;
}
};
class Derived: public Base {
public:
int value2;
// default constructor:
Derived () {
value2 = 0;
}
};
int main () {
Derived *derived = new Derived;
derived->value2 = 20;
Base *base = new Base;
base->value1 = 10;
cout << "value1 of base is " << base->value1 << endl;
// now try assigning Derived to Base:
// Derived *derived = (Base*)derived;
// OR
// Derived *derived = base;
// you will get a compilation error
// we can do the following line for sure
base = derived;
// as long as there is at least one virtual member is class Base,
// we can do the following dynamic cast
derived = dynamic_cast<Derived *>(base);
delete base;
delete derived;
return 0;
}
as for why there has to be at least one virtual member in class Base in order to perform dynamic cast,this is due to the Run-TIme Type Identification(RTTI).More info can be found here: http://en.wikipedia.org/wiki/Run-time_type_information