suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- enabling access to the private data members in the base class. How is this possible since it is mentioned that a derived class cannot inherit private data members
Because the getters and setters are public
-- they're callable by anyone, not just derived classes.
A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares.
The derived class does not inherit the private members but can access them via the getters and setters that in the base class. Control is still in the base class.
Getters and setters do Not give you complete control over private data members. The control still lies with the base class.
Using the pattern
class MyClass {
private: int a;
public: void setA(int x) { a = x; }
public: int getA() const { return a; }
};
seems object-orientated and has the sent of encapsulation.
However as you noticed, you can still directly access the private field and there is nothing gained over just making a
public and accessing it directly.
Using getters and setters like this does not really make sense in C++.
It depends on the inheritance type. If you inherit privately, then the derived class does NOT have access to the Base's private members.
Access public protected private
-----------------------------------------------------------
members of the same class yes yes yes
members of derived classes yes yes no
not members yes no no