Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ Inheritance

Started by Thomo Jan 10, 2007 at 4:49 AM 3 replies 800+ views
Original Post
Thomo
Thomo
How do I access the members of a derived class object when I only have the base class instance?
Ro_Akira
Ro_Akira
With static_cast or a C-style cast, you must be sure it is actually the object your casting to. If you're not 100% sure, you should use dynamic_cast instead. At least you can handle failure more gracefully that way.
Rossguy
Rossguy
Or are you asking how to use virtual functions?

To extend from the AP's post:

class Superclass {    // methods and data...etc..    virtual void MyMethod();};class Subclass : public Superclass {    // subclass's member functions and data    virtual void MyMethod();};// now you can doSuperclass* p;p = new Subclass();p->MyMethod();// and it will call Subclass's implementation of MyMethod(), // despite being a Superclass *
Glak
Glak
"How do I access the members of a derived class object when I only have the base class instance?"

That is almost always a bad thing to do. You probably need to rethink your design

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.