27
class base {
    int i;
public:
    base()
    {
        i = 10;
        cout << "in the constructor" << endl;
    }
};

int main()
{
    base a;// here is the point of doubt
    getch();
}

What is the difference between base a and base a()?

in the first case the constructor gets called but not in the second case!

3 Answers 3

42

The second one is declaring a function a() that returns a base object. :-)

Sign up to request clarification or add additional context in comments.

Comments

23

base a declares a variable a of type base and calls its default constructor (assuming it's not a builtin type).

base a(); declares a function a that takes no parameters and returns type base.

The reason for this is because the language basically specifies that in cases of ambiguity like this anything that can be parsed as a function declaration should be so parsed. You can search for "C++ most vexing parse" for an even more complicated situation.

Because of this I actually prefer new X; over new X(); because it's consistent with the non-new declaration.

1 Comment

But does new X; act the same as new X()?
-6

In C++, you can create object in two way:

  1. Automatic (static)
  2. Dynamic

The first one uses the following declaration :

base a; //Uses the default constructor
base b(xxx); //Uses a object defined constructor

The object is deleted as soon as it get out of the current scope.

The dynamic version uses pointer, and you have the charge to delete it :

base *a = new base(); //Creates pointer with default constructor
base *b = new base(xxx); //Creates pointer with object defined constructor

delete a; delete b;

4 Comments

Shouldnt it be base * a = new base() ??
Is this answer really relevant to the question? You didn't address base b()
What is the proper way for dynamically allocating an object using a default constructor in C++? Is it base* a = new base(); OR base* a = new base;? What's the difference?
You can see that at : stackoverflow.com/a/620402/637404

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.