Search code examples
c++inheritancecastingimplicit-conversionexplicit-conversion

Why does the cast operator to a private base not get used?


In this code assigning to b1 works, but it won't allow assigning to b2 (with or without the static cast). I was actually trying to solve the opposite problem, public inheritance but not implicitly converting to the base. However the cast operator never seems to be used. Why is this?

struct B {};    

struct D1 : private B {
    operator B&() {return *this;}
    B& getB() {return *this;}
};

struct D2 : public B {
    explicit operator B&() {return *this;}
};

struct D3 : public B {
    operator B&() = delete;
};

void funB(B& b){}

int main () {
  D1 d1;
  funB(d1.getB()); // works
  // funB(d1); // fails to compile with 'inaccessible base class
  D2 d2;
  funB(d2); // works
  D3 d3;
  funB(d3); // works 
  return 0;
}

Solution

  • From [class.conv.fct]:

    A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.

    So in your first example:

    struct D1 : private B {
        operator B&() {return *this;}
        B& getB() {return *this;}
    };
    

    operator B& will never be used because it converts to a base class. It doesn't matter that it's a private base class.