I have this simple code:
class A {
public:
int m;
};
class B : public A {
public:
B(const B& b) { /*...*/ }
B(const A& a) { /*...*/ }
int n;
};
const A& function()
{
static A a;
return a;
}
int main()
{
const B& a = function();
const int x = a.n; // !!!!! Error: probably reads some random mess
/* ... */
B b2 = function();
/* ... */
return 0;
}
In this code I demonstrate what can happen when you mistakenly write const B& a = function()
instead of const A& a = function()
. And the compiler does not catch this error! To catch this error at compile time, constructor B(const A& a)
must be explicit
. But marking constructor explicit
disables ability to do B b2 = function();
— it must be written uglier: B b2(function());
Question: Does there exist some way to catch this type of error at compile time while keeping the possibility to write this?
B b2 = function();
EDIT: As is stated by @ditskowitch and @n.m. - what i am supposing to be error is not error. For that, explicit contructor is not needed. It can teoreticaly be problem only if depending code expects that reference returned by function() points at some address as showed by @Rory Yorke