(C++)Why does calling a method from within another method use the version that is within the same class and not an overriden version?

  c++

I have made an example that shows exactly my point without any additional code from my actual project. I have two classe 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 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.

Source: Windows Questions C++

LEAVE A COMMENT