Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Public method in public inheritance becomes private in C++

I have a base class with a public method, but when I try to call it from a derived class which inherits publicly from the base class it becomes private. How is it possible? Shouldn’t public inheritance means that public methods are kept public?

These is the base class and the method I am referring to is the method r() specifically

class Potential {
public:
    Potential() {}
    double r() const {return 0;}
};

and this is the derived class

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class HammachePotential : public Potential {
public:
private:
    double r;
};

int main()
{
    HammachePotential a;
    a.r();
}

Edit:
The compiler output is

<source>:16:7: error: 'double HammachePotential::r' is private within this context
   16 |     a.r();
      |       ^
<source>:10:12: note: declared private here
   10 |     double r;
      |            ^
<source>:16:8: error: expression cannot be used as a function
   16 |     a.r();
      |     ~~~^~

I will soon try to reproduce a minimal example of it and see how it goes. I am sorry, but I am new asking questions here.

>Solution :

you have a private member variable r in HammachePotential which shadows the method in Potential. Make sure to check the full error message from your compiler, GCC at least gives enough hints to work this out:
https://godbolt.org/z/bbv5v9feh

<source>:188:7: error: 'double HammachePotential::r' is private within this context
  188 |     a.r();
      |       ^
<source>:162:12: note: declared private here
  162 |     double r;
      |            ^
<source>:188:8: error: expression cannot be used as a function
  188 |     a.r();
      |     ~~~^~
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading