mercredi 21 juillet 2021

Making Base Class Conversion Functions Public with a Protected Inheritance

I have a class inheriting from another. I don't want users of this class to accidentally use base-class functions on the child object. The obvious answer is to make the inheritance protected or private.

However, I do want implicit casting from the child object to the base class. The default implementation of this cast is hidden in most contexts as it's given the protected/private status, and attempting to define a user conversion throws the warning that "converting ‘B’ to a reference to a base class ‘A’ will never use a type conversion operator [-Wclass-conversion]"

Fair enough. With that avenue closed to me, I must turn here and ask: is there some way to reclassify the default type conversion into the public space so that implicit casting can live on?

As an example of what I'm trying to get working:

class A
{
public:
    A()
    {
        
    }
    A(A& otherA)
    {
        
    }
};

class B : protected A
{
public:
    operator A& ()
    {
        return *this;
    }
    
};

int main() {
    B guy;
    A otherguy(guy);
}

Sadly, I can't just declare the offending functions within the base class as protected: I want them available if the user explicitly casts to that base class. In my particular case, B contains no data and is merely a convenience/safety wrapper around A, so I don't need to worry about slicing or otherwise losing any information by allowing this cast. I just don't want users mistaking the backend API (which is exposed currently via public inheritance) for parts of the more user-friendly wrapper API.

Aucun commentaire:

Enregistrer un commentaire