I have made an example that shows exactly my point without any additional code from my actual project. I have two classes that are parent and child and each have a getClass()
method that return a string with the name of their class. Obviously the getClass()
method inside the child overrides the one in Parent. Then I have an additional method getClass2()
that instead returns the string that is returned from getClass()
. Right now it doesn't make sense why I would do that, but as I mentioned this is a simplified example. This is my code:
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
string getClass(){
return "I'm a Parent";
}
string getClass2(){
return getClass();
}
};
class Child : public Parent
{
public:
string getClass(){
return "I'm a Child";
}
};
So what happens is that i create two objects, one of each class and then i call the methods getClass() and getClass2 once for each of them.
int main()
{
Parent p;
Child c;
cout << p.getClass() << endl;
cout << c.getClass() << endl;
cout << p.getClass2() << endl;
cout << c.getClass2() << endl;
return 0;
}
The getClass() calls work as intended and print:
I'm a Parent
I'm a Child
But the getClass2() calls both print the same thing:
I'm a Parent
I'm a Parent
So my question is why does calling a method(getClass) from within another method(getClass2), use the version that's inside the Parent class and not the overriden version inside the Child class.
NOTE: I care more in how it works that how to fix it. Thanks in advance to whoever can offer me help.