JimRaid JimRaid - 1 year ago 44
C++ Question

How to speak to a inherit class from another inherit class

Here to show you what I mean exactly it hard to describe without code:

class Object
// attributes..

class Attribute
void myfunc();

class Character: public Object, public Attribute


void main()
Object* ch = new Character;
// How can I call the myfunc() from Attribute
// tried static_cast<Attribute*>(ch);

I only just have a Object Class pointer and i doesn't know
if it is a Character Object or another object which inherit from the
Attribute class, what i know is that the class inherit from Attribute Class.

Answer Source

Cross casting can only be done by dynamic_cast.

Object * o = new Character;
Attribute * a = dynamic_cast<Attribute*>(o);

if (!a) throw_a_fit();


However, for this to work you must have polymorphic base classes (they must have at least one virtual function).