Classes part 12-Explicit ctor and list initialization to avoid conversions| Modern Cpp Series Ep. 48

preview_player
Показать описание

►Lesson Description: In this lesson I show you two tips to make your C++ a little bit safer by avoiding conversions. The 'explicit' keyword avoids implicit conversions when constructing single parameter objects. Using curly braces (list initialization) can also be used when instantiating new instances of objects to avoid narrowing conversions of your object.

►Please like and subscribe to help the channel!
Рекомендации по теме
Комментарии
Автор

I have been learning a lot of great C++ from you channel! Loving the classes series

dwolrdcojp
Автор

Hi, Mike! Thanks for the tutorial!
I changed the code a little bit to see how udt u1 = 500; works at 4:34. My thought was on the right hand side of equal sign (i.e 500) would be constructed to udt using the constructor udt(int), so we have something like udt u1 = udt(500); and indeed that's how the compiler works (I used cpp insights to check that). However, when I made the copy constructor "explicit", the code still works which means that udt u1 = udt(500); wouldn't call the copy constructor. I wonder why??

Below is my code:

#include <iostream>
class UDT {
public:
UDT() {
std::cout << "constructor UDT() is called" << std::endl;
}
UDT(int a): m_a(a){
std::cout << "constructor UDT(int a) is called" << std::endl;
}
explicit UDT(const UDT& u){
std::cout << "copy constructor called" << std::endl;
m_a = u.m_a;
m_b = u.m_b;
}
int m_a;
double m_b;
};

int main() {
UDT u = UDT(10); // this works
//UDT u1(5);
//UDT u2 = u1; //error
UDT u3 = 500; // this works and is equal to UDT u3 = UDT(500);
return 0;
}

Thanks in advance!

維仁陳-ck
Автор

Hallo Mike, great video!
you have not explained why we have different behaviours with parenthesis, =(equal sign ) and curly braces.
Can you please make video about Aggregation, Composition and Association.
Thank you.

blaisofotso
Автор

Very well explained as always. Thank You.

dhanushs