Fabio Dalla Libera
Fabio Dalla Libera

Reputation: 1326

Making the parent private and the grandparent public for a class

Short story:

is it possible to do

class A{};
class B:public virtual A{}; 
class C:public virtual A,private B{};

i.e. "showing" that C is an A and not a B, but making it actually a B without adding the virtual (and the corresponding vptrs)?

Long story: A has several methods. B adds some more. Sometimes I want to forbid the use of one of them. C has this purpose. The program has many B, few Cs. I do not want then to make B a subclass of C.

Upvotes: 1

Views: 119

Answers (1)

anatolyg
anatolyg

Reputation: 28300

Yes, this will do exactly what you intend it to do. But consider another option: inheriting publicly and hiding the unwanted methods:

class A
{
public:
    int a() {return 0xaa;}
};

class B: public A
{
public:
    int b() {return 0xbb;}
};

class C: public B
{
private:
    using B::b; // makes the method called b private
};

...
B().b(); // OK, using method b in class B
C().b(); // error: b is private in class C
C().B::b(); // OK: calling b in base-class (not sure if you want to prevent this)

This will work with both virtual and non-virtual inheritance.

Upvotes: 1

Related Questions