This question already has an answer here:
- C++ overridden function not called 3 answers
Sorry if the name is a bit confusing. I come from a Java Background, but I've noticed that polymorphism is handled a little differently in C++
I have the code below;
class BaseClass
{
public:
void printOut()
{
std::cout << "this is the Base Class" << endl;
}
};
class DerivedClass :
public BaseClass
{
public:
void printOut()
{
std::cout << "this is the Derived Class" << endl;
}
};
These are two simple classes I've created to test polymorphism with.
The main function is as follows
BaseClass base;
base.printOut();
DerivedClass derived;
derived.printOut();
BaseClass *pBase = &derived;
pBase->printOut();
The output I get from this is;
this is the Base Class
this is the Derived Class
this is the Base Class
Coming from a Java background, this is a bit odd to me as even though I have upcasted the derived class, it should still print this is the Derived Class
as it's content should still be the Derived Class, but with a different identification.
However, in this case, it was not as I expected, and it seems to have gone by it's pointer definition, and printed this is the Base Class
instead.
How would i achieve the desired result in C++?
Aucun commentaire:
Enregistrer un commentaire