6

Possible Duplicate:
Default constructor with empty brackets

This is the code that I worked on and I don't understand what it's happening on constructor Package obj2(); On output are displayed 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);

}
Community
  • 1
  • 1
laura
  • 2,085
  • 13
  • 36
  • 68

3 Answers3

8

This does not declare an object:

Package obj2();

Believe it or not, it declares a function that returns a Package object. It's called "the most vexing parse."

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
4

Line

Package obj2();

needs to be

Package obj2;

More info

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

or, alternative take on this (from Google cache, real site was down, and take it with a grain of salt, it raises good points but does its best to make them sound worse than they are):

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

hyde
  • 60,639
  • 21
  • 115
  • 176
4

If you are using C++11, and want to solve the 'most vexing parse' problem, you can replace

Package obj2();

with

Package obj2{};

This is part of the uniform initialization syntax of C++11, which was designed primarily to get around this problem.

Robin McCorkell
  • 744
  • 6
  • 22