The dynamic_cast
is not working for two reasons.
One is that, as you guessed, you need virtual functions for dynamic_cast
to work, which is to say that the base type myclass
must be polymorphic.
The other reason also addresses your second question. In your code, derivedclass
inherits from myclass
. This implies that any object of type derivedclass
is also an object of type myclass
. It does not imply that any object of type myclass
is necessarily also of type derivedclass
, which you seem to be assuming.
// creates a new instance of myclass, NOT an instance of derivedclass
myclass* p= new myclass;
// assuming myclass is polymorphic, returns a type-safe pointer to a derivedclass object
// if p is not such an object, returns nullptr, which is useful for error checking
derivedclass* pd1 = dynamic_cast<derivedclass*>(p);
// this is very unsafe! pd2 is now a 'wild' pointer to an object that doesn't exist
derivedclass* pd2 = static_cast<derivedclass*>(p);
// this is Undefined Behavior: there is no such `b` in memory at pd2, and that memory
// is not yours to read from
cout << pd2->b << endl;
The reason that pd->b
is not -2
is because the constructor of derivedclass
never ran. You never created an object of derivedclass
.