Constructor problem

Possible duplicate:
The default constructor with empty brackets

This is the code I was working on, and I don’t understand that this is happening in the Package obj2 () constructor; The output displays only the values ​​4 (package obj1 (4)) and 2 (package obj3 (2))

#include <iostream> using namespace std; class Package { private: int value; public: Package() { cout<<"constructor #1"<<endl; value = 7; cout << value << endl; } Package(int v) { cout<<"constructor #2"<<endl; value = v; cout << value << endl; } ~Package() { cout<<"destructor"<<endl; cout << value << endl; } }; int main() { Package obj1(4); Package obj2(); Package obj3(2); } 
+6
source share
3 answers

Line

 Package obj2(); 

should be

 Package obj2; 

Additional Information

http://www.parashift.com/c++-faq/empty-parens-in-object-decl.html

or, an alternative to take this (from the Google cache, the real site was down, and take it with salt, it raises good points, but does everything possible to make them worse than they are):

http://webcache.googleusercontent.com/search?q=cache:http://yosefk.com/c%2B%2Bfqa/ctors.html#fqa-10.2

+4
source

This does not declare an object:

 Package obj2(); 

Believe it or not, it declares a function that returns a Package object. He called "the most unpleasant analysis .

+8
source

If you use C ++ 11 and want to solve the problem of "the most unpleasant parsing", you can replace

 Package obj2(); 

from

 Package obj2{}; 

This is part of the syntax syntax for C ++ 11 that was designed primarily to solve this problem.

+4
source

All Articles