1

Originally the base class B was derived from class A. But as C derives from both A and B I got into a nasty diamond shaped inheritance and thus removed the inheritance in B opting for a conversion function to A.

Now I'm getting warnings for classes of typ C, due to conversion to base classes never being used. How can I fix or remove those? The program runs without issues.

// base class providing most functionality
class A{
public:
int doStuff(){ return 0; };
};

// pure virtual interface providing a conversion to A
class B{
public:
virtual operator A&()=0;
};

// interface implementation
class C: public A, public B{
public:
virtual operator A&() override{return *this;}
};

warning: conversion function converting 'C' to its base class 'A' will never be used

        virtual operator A&() override{return *this;}
                ^
Phyr
  • 47
  • 4
  • What about virtual inheritance instead? If both `B` and `C` inherit virtually from `A` you will end up with one sinlgle `A` instance in `C`... – Aconcagua Jul 26 '21 at 11:01
  • `C c; A& a = c;` won't use your `operator A&`; using other naming might be a possibility. – Jarod42 Jul 26 '21 at 11:01
  • Maybe even simpler: Is there any reason `B` should not *publicly* inherit from `A`? If not, just do so, and if `C` then inherits publicly from `B`, it gets the inheritance from `A` automatically, so why should it explicitly inherit from `A` *again* then? – Aconcagua Jul 26 '21 at 11:10
  • Because my case is a little more complicated where C doesn't inherit from A, but a class derived from A instead. The different typ C classes all inherit from a different class derived from A. The interface B is only used in terms of methods provided by A. – Phyr Jul 26 '21 at 11:20
  • Well, you then should have described your problem as such: `D` inherting from `B` and `C` where both of the latter ones inherit from `A`. But then again: Let `B` and `C` both *virtually* inherit from `A` and you are out of trouble: `D` receives a single instance of `A`. Or is it the case that you cannot modify `C` (as you obviously could `B`)? – Aconcagua Jul 26 '21 at 11:23

1 Answers1

1

Given an instance of C, your compiler is perfectly capable of converting it to a reference to A, without needing this conversion function. The implicit conversion will be used, and this operator overload will never be used, that's literally what the compiler diagnostic says.

If your goal here is to have B's methods obtain a reference to the related A object, then the simple solution is to use a regular function, instead of an overloaded operator for this:

class B{
public:
virtual A& get_a()=0;
};

// interface implementation
class C: public A, public B{
public:
virtual A& get_a() override{return *this;}
};

Other methods in B will simply need to use get_a(), explicitly. But, if you so wish:

class B{
public:
virtual A& get_a()=0;
operator A&() { return get_a(); }
};
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148