Limited inheritance

This is just a thought. Say I have a class Foo, and a class Child that inherits Foo. Is it possible to declare a function in Foo that Child does not inherit without making it private?
OK, I'm not going to go into the reasons why you shouldn't do that, because I assume you already know (Liskov Substitution Principle and such). IMO there is not much that can be done that solves your problem, assuming that you wanted to abuse the inheritance mechanism in this way.

The dirty solution is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//intended for the clients of A
class A {
public:
    void method () {}
    void message () {}
};

//intended for the derivatives of A
class B : public A {
private:
    using A::method;
};

//an example, albeit trivial derivative of A through B
class C : public B {
};

int main()
{
    C c;
    c.message();
    c.method(); //yields error 'void A::method()' is inaccessible
}

This also requires reintroducing all parametrized constructors from A in B, by simply redirecting them to the base. This is major nonsense. Notice also that C::method exists in C, but is just not accessible.

The cleaner approach is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//intended for inheritance from A
//(can be made non-user-instantiable with protected constructor)
class A {
public:
    void message () {}
};

class B : public A {
public:
    void method () {}
};

class C : public A {
};

int main()
{
    C c;
    c.message();
    c.method(); //yields error 'class C' has no member named 'method'
}

You will need protected alternative of A::method in A, if A::message has to use A::method in its implementation. Here C::method does not even exist (access has nothing to do with that.)

Regards
Last edited on
Wow, thanks! I'll read up on the Liskov Substitution Principle;)
Topic archived. No new replies allowed.