[cfe-dev] "Mutable base class": Operator to base class "will never be used"

Gustaf Räntilä g.rantila at gmail.com
Tue Dec 21 05:45:14 PST 2010


Hi,

I have a question regarding operators to base classes, or rather, how
clang sees them. I stumbled upon the situation where I wanted a base
class to be basically "mutable" (in my case a Mutex class). One can
argue about the uglyness in such a solution, but I cannot get over the
fact that this doesn't compile, and what surprises me is the warning
clang gives me.

Consider the following, a simple class A with an int and a function,
and an empty class B inheriting A:

class A {
public:
	A() : i(17) {}
	void f() {}
	int i;
};
class B : public A {
public:
	B() {}
	operator A&() const { return (A&)*const_cast<B*>(this); } // warning:
conversion function converting 'B' to its base class 'A' will never be
used
	operator int&() const { return const_cast<B*>(this)->i; } // However
this is fine
};

int main(int argc, char** argv) {
	B b;
	const B& cb = b;
	int& i(cb); // This is a valid implicit cast
	A& a(cb); // error: binding of reference to type 'A' to a value of
type 'B const' drops qualifiers
	a.f();
}

Is there some part of the language saying that an operator to a
reference of a class which happens to be a base class, is not valid
(or rather valid but "not used")? I'm not sure, so I don't want to
file a bug report, but rather let you analyze it first.

I can (almost) understand that C++ wants to own the right to casts
from B& to A& or at least use the default cast (static cast I
suppose), but in this case, I want to implicitly cast from "const B&"
to "A&" for which there is no default cast, using my operator. What
exactly is it I don't get?
I understand the error because of the warning, but I don't understand
the warning, or rather *why* I get the warning. A description of why
the "conversion function" will never be used, would be suitable, in
clang's output.

This is clang 2.8 from 64-bit vanilla Ubuntu 10.10.

Gustaf



More information about the cfe-dev mailing list