Now I would like to copy objects of the inherited classes from one to another, without having to de-cast them.
Is there a way to do that?
The following example shows what I would like to do (but what doesn't work this way):
/**
test how to copy inheritated objects
*/
#include <cstdlib>
#include <cstdio>
class Fruit
{
public:
virtual const char* get_name()
{
return "(nothing)";
}
};
class Apple: public Fruit
{
public:
const char* get_name()
{
return "Apple";
}
};
class Orange: public Fruit
{
public:
const char* get_name()
{
return "Orange";
}
};
int main(int argc, char *argv[])
{
printf("Test inheritation \n");
Fruit *myfruit1 = new Apple();
Fruit *myfruit2 = new Orange();
Fruit *myfruit3 = new Apple();
printf("myfruit1 = %s \n", myfruit1->get_name()); // prints "Apple"
printf("myfruit2 = %s \n", myfruit2->get_name()); // prints "Orange"
printf("myfruit3 = %s \n", myfruit3->get_name()); // prints "Apple"
// The following does not work
printf("Now change myfruit3 from Apple to Orange... \n");
*myfruit3 = *myfruit2;
printf("myfruit3 = %s \n", myfruit3->get_name()); // prints "Apple" but should print "Orange"
delete myfruit1;
delete myfruit2;
delete myfruit3;
system("pause");
return EXIT_SUCCESS;
}
(o, and don't bother about the physical interpretation of the example - it is just an example

New Topic/Question
Reply



MultiQuote






|