+ 1
Initializer list don't need parametric constructor?
Hi I thought classname obj{Val} is initializer list..... So, what is classname obj = {Val} Does second option i.e. with equal to call implicit constructor ? #include <iostream> using namespace std; class X { public: int x; explicit X(int x) : x(x){} }; int main() { X a = {10}; X b = a; cout << a.x << " " << b.x << endl; return 0; } Above code only work if I remove explicit keyword .... Also why it build without no parametric constructor as well ?
4 Respostas
+ 1
this "explicit" makes you unable to copy-initialization. You have to make it "X a(10)" and "X b(a)" so it is direct-initialization. You can use static_cast too, like "X c = (X)5"
+ 1
About implicit constructor, I'm not sure about that, but implicit constructor (copy constructor in this example) can actually work, try
X a(10); //calling directly constructor
X b = a; // copy constructor
Idk if it works tho
0
I got your point , but does it not required to have parametric constructor ? Assignment will work as it is generated by default... Does parametric constructor also generated by default due to initializer list ?
0
Not really, assignment is not generated by default. If you use inline constructor (generated by default), you have to assign values in class declaration like that:
public:
int x {0};
Then you do not need your own parametric constructor.
Is it what were you asking for?