Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does private inheritance always mean "HAS-A"?

According to my favorite author , Mr Scott Meyers, the private inheritance and composition means the same thing aka Has-A relationship. Thus everything that can be gained from composition (containment, when class A has class B as its member) can be gained by private inheritance, and visa-versa.

So the following code should be a Has-A relationship, but from my point of view, its not!

class A : private boost::noncopyable {.. this is irrelevant };

Can anyone please tell me that I am missing? Or how this code can be implemented through composition?

like image 664
Eduard Rostomyan Avatar asked Jun 04 '18 12:06

Eduard Rostomyan


People also ask

What does private inheritance mean?

Private Inheritance. Private Inheritance is one of the ways of implementing the has-a relationship. With private inheritance, public and protected member of the base class become private members of the derived class. That means the methods of the base class do not become the public interface of the derived object.

What is difference between public and private inheritance?

A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member. A private member variable or function cannot be accessed, or even viewed from outside the class.

What is the difference between protected inheritance and private inheritance?

protected inheritance makes the public and protected members of the base class protected in the derived class. private inheritance makes the public and protected members of the base class private in the derived class.

Are private members of a class inherited?

Private members are accessible only within the class in which they are declared. So even if you inherit the class, you will have access only to the public and protected members of the base class but private members are not inherited(accessible).


1 Answers

You example can be implemented through composition like this:

class A {
private:
    class B {
        B(const B&) = delete;
        B& operator=(const B&) = delete;
    } b;
};

A is noncopyable, because its member b is noncopyable.

like image 137
VLL Avatar answered Sep 29 '22 17:09

VLL