Pointer/Inheritance Difficulty

Started by
6 comments, last by knowyourrole 18 years, 3 months ago
Hello. I have a small problem with my current project, and I'm sure there is a simple answer I'm ignorant of. Anyways, my problem is: Can I use a pointer to a base class, to hold a pointer to a derived class? If so, how can I access the contents of this derived class, using the base class pointer? This is for an event system, where there is a generic Event class, which holds a pointer to an EventData class. This EventData class has some diffrent classes derived from it. Basically, I need this EventData pointer to be able to hold any one of the derived data classes, and be able to access the various contents through that pointer. It seems like it should be simple/possible, but I've just hit neverending problems with this. Any help would be appreciated :)
Advertisement
Quote:Original post by knowyourrole
Can I use a pointer to a base class, to hold a pointer to a derived class?

Ye.

Quote:
If so, how can I access the contents of this derived class, using the base class pointer?

Cast it to a pointer to the derived type. However, this should be rarely necessary if your base class exposes a proper set of virtual functions.
Its possible and called polymorphism if im not mistaken.

BaseClass *pBase = new DerivedClass;

pBase->func1();


func1(); is a virtual function which is in BaseClass and you write it in every class you derive from BaseClass.
Something like that.
thanks for the replies.

I know of polymorphism, but for now, I'm not using a virtual function, as what I need is for each different derived class to contain diffrent types/amounts of data.

For example, one derived class may contain an integer, where the base class does not. Using a cast, I still wouldnt be able to access this integer by using the pointer to the base class, that is my problem :(
Then use the virtual functions. That's what they're there for.
Ok, so a virtual function, same function called on each derived class, to do different things right.

But they have to return the same thing, and have identical parameters, if I'm not mistaken, and I still don't see how I can use this to access the different contents of each derived class.

Say one derived class holds an integer, another holds a char, can I use a virtual function that will get at each of these attributes?
You're thinking on too low of a level. Don't use the virtual function to access the data. Have the virtual function do whatever it is that you would do with the derived class' data.
ok, I think I am beginning to understand.

Whatever it is that I need to access this data for, I should just do inside of the virtual function, therefore not having to get the data out of the pointer somehow.

That makes more sense, thanks for the push in the right direction everybody.

EDIT: Thanks SiCrane ^^, you just said exactly what I was thinking

This topic is closed to new replies.

Advertisement