Home > Software design >  call an immediate parent in c
call an immediate parent in c

Time:11-24

This is a true story of evolving code. We began with many classes based on this structure:

class Base
{
public:
    virtual void doSomething() {}
};

class Derived : public Base
{
public:
    void doSomething() override 
    {
        Base::doSomething(); // Do the basics

        // Do other derived things
    }
};

At one point, we needed a class in between Base and Derived:

class Base;
class Between : public Base;
class Derived : public Between;

To keep the structure, Between::doSomething() first calls Base. However now Derived::doSomething() must be changed to call Between::doSomething()...

And this goes for all methods of Derived, requiring search & replace to many many calls.

A best solution would be to have some this->std::direct_parent mechanism to avoid all the replacements and to allow easy managing of class topology.

Of course, this should compile only when there's a single immediate parent.

Is there any way to accomplish this? If not, could this be a feature request for the C committee?

CodePudding user response:

What I can suggest is parent typedef in Derived:

class Base
{
public:
    virtual void doSomething() {}
};

class Derived : public Base
{
private:
    typedef Base parent;
public:
    void doSomething() override 
    {
        parent::doSomething(); // Do the basics

        // Do other derived things
    }
};

Then after introduction of Between the only change needed in Derived is the change of the parent typedef:

class Derived : public Between
{
private:
    typedef Between parent;
public:
    void doSomething() override 
    {
        parent::doSomething(); // Do the basics

        // Do other derived things
    }
};

CodePudding user response:

I think this question is related to: Using "super" in C

I've seen projects, where the direct parent of the current class is mentioned as a "SUPER" typedef in the class header. This makes code-changes with new intermediate classes easier. Not bulletproof, but easier. Almost the same, as in the linked question.

  • Related