Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor without arguments doesn't work [duplicate]

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.

like image 434
James Avatar asked Mar 16 '23 14:03

James


2 Answers

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.

like image 175
OJFord Avatar answered Apr 02 '23 10:04

OJFord


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;
like image 37
emlai Avatar answered Apr 02 '23 08:04

emlai