Mr. Boy
Mr. Boy

Reputation: 63816

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.

Upvotes: 6

Views: 107

Answers (1)

dfrib
dfrib

Reputation: 73206

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.

Upvotes: 7

Related Questions