we have two classes: Base and Derived. There is a function in Base class called PrintValue() which has been defined as protected. Derived class inherits this function from Base class, but it is able to change its access specifier to public by declaring it in the public section. My question is: Is this a good software engineering practice? why is Derived class, which inherits a function from Base class, able to change the access level of that function to public, which has already been declared as protected by Base class. this way, in the main function you can declare an object of Derived class and access the protected function of Base class and this is against the expectation of Base class.
class Base
{
private:
int m_nValue;
public:
Base(int nValue)
: m_nValue(nValue)
{
}
protected:
void PrintValue() { cout << m_nValue; }
};
class Derived: public Base
{
public:
Derived(int nValue)
: Base(nValue)
{
}
// Base::PrintValue was inherited as protected, so the public has no access
// But we're changing it to public by declaring it in the public section
Base::PrintValue;
};
int main()
{
Derived cDerived(7);
// PrintValue is public in Derived, so this is okay
cDerived.PrintValue(); // prints 7
return 0;
}