C ++ virtual override functions with the same name

I have something like this (simplified)

class A { public: virtual void Function () = 0; }; class B { public: virtual void Function () = 0; }; class Impl : public A , public B { public: ???? }; 

How can I implement function () for A and function () for B? Visual C ++ allows you to define a specific built-in function (i.e. Not in the cpp file), but I assume this is an extension. GCC complains about it. Is there a standard C ++ way to tell the compiler which function I want to override?

(visual C ++ 2008)

 class Impl : public A , public B { public: void A::Function () { cout << "A::Function" << endl; } void B::Function () { cout << "B::Function" << endl; } }; 

Thank!

+19
c ++ override diamond-problem virtual
Jun 30 '10 at 14:39
source share
4 answers

You cannot use qualified names there. I am writing void Function() { ... } , you are redefining both functions. Herb Sutter shows how this can be solved .

Another option is to rename these functions, because, apparently, they do something else (otherwise I do not see the problem of redefinition as with the same behavior).

+29
Jun 30 2018-10-06
source share

As a workaround, try

 struct Impl_A : A { void Function () { cout << "A::Function" << endl; } }; struct Impl_B : B { void Function () { cout << "B::function" << endl; } }; struct Impl : Impl_A, Impl_B {}; 
+2
Jun 30 '10 at 14:45
source share

I can suggest another way to solve this problem. You can add a wrapper Typed that changes the Function signature by adding a dummy file parameter. This way you can distinguish methods in your implementation.

 class A { public: virtual void Function() = 0; virtual ~A() = default; }; class B { public: virtual void Function() = 0; virtual ~B() = default; }; template<typename T> class Typed : public T { public: virtual void Function(T* dummy) = 0; void Function() override { Function(nullptr); } }; class Impl : public Typed<A>, public Typed<B> { public: void Function(A* dummy) override { std::cerr << "implements A::Function()" << std::endl; } void Function(B* dummy) override { std::cerr << "implements B::Function()" << std::endl; } }; 

The advantage of this solution is that the entire implementation is placed in one class.

0
Oct 29 '13 at 15:20
source share

If A and B are interfaces, then I would use virtual output to combine them (so that they overlap). If you need different implementations for Function , if they are called with a pointer to A or B , I would strongly recommend choosing a different project. Otherwise it will hurt.

Impl "comes from" A and B means Impl "means" A and B I suppose you don’t mean it.

Impl "implements the interface" A and B means Impl "behaves like" A and B then the same interface should mean the same behavior.

In both cases, having different behavior according to the type of pointer used, there will be a “schizophrenic” and, of course, to avoid the situation.

-one
Jun 30 '10 at 14:44
source share



All Articles