Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 507
Bas Avatar asked Mar 21 '16 13:03

Bas


People also ask

What is a cast operation?

A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator. The most general cast supported by most of the C++ compilers is as follows − (type) expression.

What are the new style cast operators in C++?

This chapter discusses the new cast operators in the C++ standard: const_cast , reinterpret_cast , static_cast and dynamic_cast . A cast converts an object or value from one type to another.


1 Answers

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.

like image 188
Barry Avatar answered Oct 17 '22 17:10

Barry