Click to See Complete Forum and Search --> : Extract a class from an Inherited Class


nineofhearts00
January 22nd, 2009, 06:38 PM
For lack of words to explain what I'm looking for, I will try to explain by code.


class CHorse
{
void Copy(CHorse aHorse);
int num1;
int num2;
}

class CBird
{
int num3;
int num4;
}

class CPegasus : public CHorse, public CBird
{
... do stuff.
}


int main()
{
CPegasus aFlyingHorse;
...do stuff with aFlyingHorse

CHorse aHorse;
aHorse.Copy(aFlyingHorse.CHorse) //I know this doesn't work.
}


I want to be able to extract the CHorse data in aFlyingHorse to use only that set of data at this point. I do not want to have to pull each variable out and copy it one at a time. Can that be done? Can you do a cast of some sort?

Thanks in advance for any help.

Buzzyous
January 22nd, 2009, 10:40 PM
Well, if you need only members and methods from the base class, just use only them...

If you need a cast, you could create a member funcion in Pegasus, or an operator, that do it.

Also, you can make Copy() accept pointers to CHorse, and make the copy work on pointers; then in the last line will do the work the following:


aHorse.Copy((CHorse*)&aFlyingHorse);

This way, you cast the pointer (casting a pointer to an instance of a class to a pointer to its mother class is legal) of CPegasus, the derived, to the CHorse type. Only CHorse member will be indirectly addressed with the pointer casted, even if it is a pointer to a CPegasus.
In the same line, in a simpler way, without calling a copy member, just do:


CHorse* convertedPegasus = (CHorse*) &aFlyingHorse;


aFlyingHorse still remains an instance of CPegasus, but the pointer can only access to the member of the class that are members of CHorse base class. Attention: this way convertedPegasus will be polymorphic anymore; so, if you call a function present in the base class but overridden in the derived CPegasus, the function that the call will be related to will refer to the original CHorse class, unless you declare in it the function that you still want to call in the derived class as virtual. Doing so, only CHorse members methods and variables will be called, but if exists an overridden version of a virtual function of CHorse in CPegasus, still will be called the method of CPegasus. This should be accomplished if the function interact with CHorse objects in a different way in CPegasus, because remember that even if pointed to by a casted CHorse pointer, aFlyingHorse still remains a CPegasus, so altering methods may need specific elaboration code proper of the derived class structure.

nineofhearts00
January 23rd, 2009, 06:43 PM
Wow. Helpful and detailed.

Thank you for the reply. I think this will work perfectly!!