Knowing that I can pass a derived object as a parameter to a function expecting a base object, even though it strips derived members, it is still suitable for my needs.
Does that also mean that I can assign a derived object to a base object using the = operator, and it will work, albeit stripping the derived members? What about in reverse? Can I assign a base object to a derived object using =, and then just have to worry about initializing the remaining derived members?
Thank you for answering all my questions. My curiosity about this topic, and polymorphism in general is peaked. I don't necessarily need the info to solve a current problem, but it seems it may be useful in the future, and it opens up options.
I wonder if using a void pointer would allow the derived object to be passed to the base function, and maintain derived members? From the chapter in the tutorial on pointers, it seems that void pointers can be used to pass generic parameters. Applying it to the code, it seems this might solve the problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
class base
{
public:
int x;
void function(void* param, int psize);
} base_1;
class derived: public base
{
public:
int y;
} parameter;
int main ()
{
// This should work:
base_1.function(¶meter, sizeof(parameter));
// or:
parameter.function(¶meter, sizeof(parameter));
//or:
base_1.function(&base_1, sizeof(base_1));
//or:
parameter.function(&base_1, sizeof(base_1));
}
void base::function (void* param, int psize)
{
if ( psize == sizeof(base) )
{
base* pbase;
pbase=(base*)param;
// operations using only *pbase.x
}
else if (psize == sizeof(derived) )
{
derived* pderived;
pderived=(derived*)param;
// operations using both *pderived.x and *pderived.y
}
}
|
Also, is there a way to do this without the sizeof() function? Perhaps by defining a string called type in the base class, and then checking against it to see what type of object the function is dealing with.