3

I have a protected method Value. In successor i overload it in a public method. Why can i do this? I think, it is a violation of encapsulation.

Example:

class Foo {
public:
    Foo(int a) : m_a(a) {};
    virtual ~Foo() {};

    void PrintValue() {
        std::cout << Value() << std::endl;
    }
protected:
    virtual int Value() {
        return m_a;
    }
private:
    int m_a;
};

class Bar : public Foo
{
public:
    Bar(int a, int b) : Foo(a), m_b(b) {};
    virtual ~Bar() {};

    int Value() override {
        return m_b;
    }
private:
    int m_b;
};

int main(int argc, char** argv)
{
    Bar b(10, 20);
    b.PrintValue();
    std::cout << b.Value() << std::endl;
    return 0;
}

Output:

20
20
Dolk13
  • 458
  • 5
  • 11
  • 2
    If it wasn't possible, nothing prevents me from making another public method which calls the protected one. You can't really protect it anyways. – deviantfan Sep 04 '15 at 14:14
  • You don't even need to override. A derived class can expose an inherited protected method via a [using declaration](http://en.cppreference.com/w/cpp/language/using_declaration). If you don't want derived classes to see something, make that something private. – David Hammen Sep 04 '15 at 14:57

1 Answers1

3

Because the visibility/access modifier isn't inherited.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621