0

I have a diamond design currently, and I saw a related question here

In that question, let me assume that class B and class C are virtual inherited from Class A, so in Class D, when we need to call virtual functions, we need to specify which one needed to call.

D::foo()
{
  B::foo(); //specify foo() in B
}

For my diamond design, I have a lot of virtual functions to rewrite, in order to let these functions called by correct B or C father class functions.

It is not good, a lot of repeated work need to be done, when I have child class, do you have some better solutions, so that I can call foo() of B in class D but no rewrite for the example above.

Community
  • 1
  • 1
CJAN.LEE
  • 1,108
  • 1
  • 11
  • 20

2 Answers2

1

Since C++11, you can do an aliasing:

class A
{
    public:
        virtual void foo() { cout << "A" << endl; }
}


class B : public virtual A
{
    public:
        void foo() { cout << "B" << endl; }
}


class C : public virtual A
{
    public:
        void foo() { cout << "C" << endl; }
}

class D : public B, C
{
    using B::foo;
}

This way, doin:

D obj;
obj.foo();

Will output B;

Henrique Barcelos
  • 7,670
  • 1
  • 41
  • 66
-3

I think template classes might do the trick here.

http://www.cplusplus.com/doc/tutorial/templates/

ordahan
  • 187
  • 9
  • How should it help here? – leemes Nov 15 '13 at 23:14
  • then again, reading the problem again seems I thought you try to address the problem which you have many inheriting classes, D1,D2 etc and some use A and some use B. Or the case when A and Black have different specified roles for each of them. – ordahan Nov 16 '13 at 22:47