Reputation: 125
Here to show you what I mean exactly it hard to describe without code:
class Object
{
// attributes..
};
class Attribute
{
public:
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.
Upvotes: 1
Views: 113
Reputation: 477080
If you know that you have an object of the correct type, you can cast explicitly:
Object * ch = /* something that's a Character */
static_cast<Attribute *>(static_cast<Character *>(ch))->myfunc();
Obviously this will not be correct if the type of the most-derived object pointed to by ch
is not a subtype of Attribute
.
If your class hierarchy is polymorphic (i.e. has at least one virtual function in each base class that you care about), then you can use dynamic_cast
directly at runtime and check if it succeeded, but that is a comparatively expensive operation. By contrast, the static cast does not incur any runtime cost at all.
Upvotes: 2
Reputation: 40859
Cross casting can only be done by dynamic_cast.
Object * o = new Character;
Attribute * a = dynamic_cast<Attribute*>(o);
if (!a) throw_a_fit();
a->myfunc();
However, for this to work you must have polymorphic base classes (they must have at least one virtual function).
Upvotes: 3