Search code examples
c++inheritancemultiple-inheritancecompiler-warnings

Fix warning "unused conversion function" in derived class


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;}
                ^

Solution

  • 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(); }
    };