Reputation: 3493
I'm working on a project where I have 2 classes: Room and EventRoom EventRoom inherits from Room and have a few more members.
In my code I do this(tmpPtr is a Room-pointer):
if(eventRoom)
tmpPtr = dynamic_cast<EventRoom*>(tmpPtr);
and later when I try this:
if(line == "false;")
tmpPtr->setComplete(false);
I get compilation errors. setComplete is a member of EventRoom
Short version: I want to create objects of type Room, and in some cases EventRoom. The code currently works for Room only, but 90% of the code would be identical for EventRoom. Any way of using the same code? (with dynamic_cast or something similiar)
Upvotes: 0
Views: 89
Reputation: 171117
The code which has to work with both Room
and EventRoom
(that is, it only works with the Room
interface), has to work through a pointer statically typed Room*
.
The code which uses specifics of EventRoom
has to work through a pointer statically typed EventRoom*
. So example code could look like this:
void someFunction(Room *myRoom) {
// doRoomStuff must be a function declared in Room.
myRoom->doRoomStuff();
// Try to determin if the room is an event room or not. This will
// occur at runtime.
EventRoom *myEventRoom = dynamic_cast<EventRoom*>(myRoom);
if (myEventRoom) {
// doEventRoomStuff is a function declared in EventRoom. You cannot call
// myRoom->doEventRoomStuff even if 'myRoom' points to an object that is
// actually an EventRoom. You must do that through a pointer of type
// EventRoom.
myEventRoom->doEventRoomStuff();
// doRoomStuff2 is a function that is declared in Room. Since every
// EventRoom is also a room, every EventRoom can do everything that
// rooms can do.
myEventRoom->doRoomStuff2();
}
myRoom->doRoomStuff3();
}
You can access Room
members through a EventRoom*
variable, but not vice versa.
Upvotes: 1
Reputation: 227390
You need tmpPtr
to be an EventRoot
pointer.
EventRoom* tmpPtr;
if(eventRoom)
tmpPtr = dynamic_cast<EventRoom*>(tmpPtr);
You can only call Room
public methods on a Room
pointer. You cannot call EventRoom
-only methods.
Upvotes: 3