C++: Strange Inheritance scenario: public members with same name

Consider this code:

#include <iostream>
#include <string>
using namespace std;
 
class Grandpa{
public:
    Grandpa() : m_BothersomeField("Grandpa") {}
    virtual ~Grandpa(){}
 
    string m_BothersomeField;
};
 
class Son: public Grandpa{
public:
    Son() : m_BothersomeField("Son") {}
    virtual ~Son(){}
 
    string m_BothersomeField;
};
 
class Grandson: public Son{
public:
    Grandson(){}
    virtual ~Grandson(){}
};
 
int main(){
        
      Grandson n;
      cout << "Grandson, no disambiguation: " << n.m_BothersomeField << endl;
      cout << "Grandson, with disambiguation (Son): " << n.Son::m_BothersomeField << endl;
      cout << "Grandson, with disambiguation (Grandpa): " << n.Grandson::m_BothersomeField << endl;
      return 0;
}

Let's ignore for a while the fact that we have public fields (breaking encapsulation). Let's suppose that we don't write this kind of code, but we can run into legacy code that does something similar.

What this code shows is what happens when a class (Grandson) inherits a public field (m_BothersomeField) from a direct ancestor (Son), and at the same, an ancestor of the direct ancestor (Grandpa) has a public field of the same name. Which of both does Grandson inherit?

I ran this test in a very neat online compiler and runner, and the output shows that Grandson inherits BOTH fields. If we don't explicitly say which one to use using the scope operator (::), C++ assumes that we mean the one that belongs to the closest ancestor (Son).

Anyway, for completeness' sake, it would be nice to run this code in another environment (MSBuild, g++, mingw). Or even better, look at the C++ standard to see if there is a standard defined behavior for this scenario.

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x