Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion and upcasting

I want to fully understand conversions, i.e. to be sure I know when does a function call would cause an implicit conversion, and when would it cause a compilation error. I've learnt that a conversion may be done if and only if there is a singular way to convert the variable with up to two steps from the following list (sorted by priority):

1. Exact match
2. Promotion
3. Conversion
4. User defined conversion

Where, the way I understood it (you may correct me), is that promotion is a conversion of primitives into bigger primitive types, such as short to int, float to double, etc; Conversion is any conversion between primitives which isn't promotion, such as int to char, etc; And user defined conversions are conversions of classes using conversion constructors and conversion operators. Now, I also know that inheritance means and Is-A relationship, meaning that a derived class is base class, and so sending a derived class to a function which expects a reference to a base class should work. Combining the two concepts above, we should get that the following example I wrote, should work:

class C {};
class D: public C
{
public:
D(int x){}
};
void f(C& c) {}
f(3);

Since D can be converted-to from int, and a D is a C. But this code isn't being compiled. Why is that? How can the contradiction be resolved? Can you shed some light on the matter? Thanks!

like image 963
Idan Avatar asked Sep 09 '26 16:09

Idan


1 Answers

The code doesn't compile because the conversion would create a temporary, which can't bind to a non-const reference.

If you pass the parameter by const reference (or by value, but I'm not suggesting you do that), it will work.

You also need a conversion constructor in the base class (explained below).

class C {
public:
   C(int x){}
};
class D: public C
{
public:
   D(int x):C(x){}
};

void f(const C& c) {}
f(3);

This is because implicit conversion only applies a maximum of one times. In your case, there is a direct conversion from int -> D and one from D -> C, so an int can't implicitly be converted to C.

like image 116
Luchian Grigore Avatar answered Sep 11 '26 07:09

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!