I wonder why the constructor doesn't work/get called in the first case.
#include <iostream>
#include <typeinfo>
class Test{
public:
Test(){ std::cout << "1\n"; };
Test(int){ std::cout << "2\n"; };
};
int main()
{
Test a(); // actually doesn't call the constructor
Test b(1); // "2"
std::cout << (typeid(b).name()) << std::endl; // "4Test"
std::cout << (typeid(a).name()); // "F4TestvE"
return 0;
}
I've also found that typenames of created variables are strange. Can anybody explain such a behavior?
I use mingw gcc 4.7.2 for Windows to compile my projects
Thanks a lot.
Test a();
Oh, that's an instantiation of a
, an object of type Test
.
Test a();
Oh, that's a declaration for a function of no arguments that returns something of type Test
.
Oh, wait...
If you instead construct a new a()
, or use an (empty) initialisation list, this ambiguity is avoided.
See Herb Sutter's excellent article for more.
Test a();
is interpreted as a declaration of a function named a
that takes no parameters and returns an object of type Test
.
To create an object, remove the parentheses:
Test a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With