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
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();
| ~~~^~