C++ diamond problem - How to call base method only once

C++ diamond problem - How to call base method only once

I'm using multiple inheritance in C++ and extending base methods by calling their base explicitly. Assume the following hierarchy:

I'm using multiple inheritance in C++ and extending base methods by calling their base explicitly. Assume the following hierarchy:

     Creature
    /        \
 Swimmer    Flier
    \        /
       Duck

Which corresponds to

class Creature
{
    public:
        virtual void print()
        {
            std::cout << "I'm a creature" << std::endl;
        }
};

class Swimmer : public virtual Creature { public: void print() { Creature::print(); std::cout << "I can swim" << std::endl; } };

class Flier : public virtual Creature { public: void print() { Creature::print(); std::cout << "I can fly" << std::endl; } };

class Duck : public Flier, public Swimmer { public: void print() { Flier::print(); Swimmer::print(); std::cout << "I'm a duck" << std::endl; } };

Now this presents a problem - calling the duck's print method calls its respective base methods, all of which in turn call the Creature::print() method, so it ends up being called twice-

I'm a creature
I can fly
I'm a creature
I can swim
I'm a duck

I would like to find a way to make sure the base method is called only once. Something similar to the way virtual inheritance works (calling the base constructor on the first call, then only assigning a pointer to it on successive calls from other derived classes).

Is there some built-in way to do this or do we need to resort to implementing one ourselves?

If so, how would you approach this?

The question isn't specific to printing. I wondered if there's a mechanism for extending base methods and functionality while keeping the call order and avoiding the diamond problem.

I understand now that the most prominent solution would be to add helper methods, but I just wondered if there's a "cleaner" way.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

C/C++ vs. Rust: A developer’s perspective

In this post, you'll see the difference between Rust and C/C++ in a developer’s perspective

Variable Introduction in C#[Bangla]

LIKE | COMMENT | SHARE | SUBSCRIBE A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a speci...