Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent grandchild calling its grandparent's methods

I have a simple parent and base class:

class X
{
public:
 virtual void Method(){...}
};

class Z : public X
{
public:
 virtual void Method(){ X::Method(); }
};

I want to refactor this so a new class Y sits in-between in the class hierarchy, so Z : Y, Y : X. Z::Method() should now call Y::Method() not X::Method(). But if I don't change this, it still compiles. In truth, I have a lot of such methods and it's very easy to miss a call to X::... when refactoring which would lead to hard-to-find bugs.

Is there a way I can get the compiler to alert me, in other words, make X's methods accessible to Y, but hidden from Z?

To clarify, this may only be a temporary change while I am doing the refactoring to make sure I don't miss anything.

like image 482
Mr. Boy Avatar asked Jan 29 '21 14:01

Mr. Boy


People also ask

Can you call a method from a grandparent class?

You can not directly access grandparent methods skipping parent methods.

Can a grandchild class call a grandparent class?

In Java, a class cannot directly access the grandparent's members. It is allowed in C++ though.


1 Answers

But if I don't change this, it still compiles. In truth I have a lot of such methods and it's very easy to miss a call to X::... when refactoring which would lead to hard to find bugs.

To clarify, this may only be a temporary change while I am doing the refactoring to make sure I don't miss anything.

As you are describing "when refactoring", you could temporarily add an incomplete type X to Z that shadows the super class X up the hierarchy:

class Z : public Y {
private:
    struct X;  // TODO(Mr. Boy): remove after finishing re-factoring.
public:
    void Method() override { X::Method(); }  // error! Z::X is incomplete
};

Any qualified use of X::... in Z will fail as lookup resolves to the incomplete nested type X.

like image 136
dfrib Avatar answered Sep 28 '22 10:09

dfrib