Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selective inheritance C++

Could you please explain why following code does compile and works fine (checked on gcc-4.3.4). I thought selective inheritance cannot weaken or even strengthen access to members/methods. Doesn't it break encapsulation rules?

#include <iostream>

class A {
protected:
    void foo() { std::cout << "foo" << std::endl;  }
};

class B : private A {
public:
    using A::foo;   //foo() becomes public?!
};

int main() {
    B b;
    b.foo();
    return 0;
}
like image 527
bkarasm Avatar asked Dec 18 '12 13:12

bkarasm


People also ask

What is selective inheritance?

Selective inheritance dependencies, or SIDs, are introduced to capture formally the inheritance of attribute values between tuples of any relation over a given relation scheme. It is shown that the membership problem, i.e., the question whether a SID is implied by a set of other SIDs, is NP-complete.

What is inheritance C?

In C++, inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class.

What is class inheritance in C?

In C, inheritance can be achieved by maintaining a reference to the base class object in the derived class object. With the help of the base class' instance, we can access the base data members and functions.


1 Answers

From the language point of view, there's nothing wrong with this (whether it's good design is another matter).

Any class can choose to expose to a wider audience things that it has access to.

In principle, your example is no different to:

class B : private A {
public:
    void bar() { foo(); }
};

except that here foo() is exposed by proxy.

What you can't do is the opposite: a publicly derived class can't restrict access to things that are accessible via the base class.

like image 114
NPE Avatar answered Sep 22 '22 17:09

NPE