Instantiating objects without calling the constructor in C++ -
this question has answer here:
- c++ default constructor not being called 2 answers
i'm new @ c++ , i'm learning constructors. have class dog constructor:
class dog{ dog(){ std::cout << "constructor called! } };
i know in c++ there different ways(if i'm not mistaken) can create object, instance:
1- dog dog; 2- dog dog = dog(); 3- dog *dog = new dog; 4- dog *dog = new dog(); 5- dog dog();
but here thing: statements 1 4 call constructor, statement number 5 doesn't , can figure out why.
do have idea why fifth statement doesn't call class constructor? thanks.
5 example of c++'s most vexing parse.
dog dog();
this declares function named dog
accepts no parameters , returns dog
. avoid most vexing parse (and if using c++11), can do:
dog dog{};
and semantically (at least until c++17), dog dog = dog();
first create temporary object (dog()
), , move construct (or copy construct, if dog
class has no move constructor) named object (dog
) it. although compilers might optimize move away, statement have different semantics rest.
if remember correctly, since c++17, p0135r0 change semantics of dog dog = dog();
has same meaning dog dog;
.
edit: pointed out @lightnessracesinorbit in comments, dog dog();
vexing, not quite vexing parse. dog dog(dog());
true vexing parse. dog dog();
a, well, plain declaration, guess.
Comments
Post a Comment