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!

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
Vijay
  • 65,327
  • 90
  • 227
  • 319

3 Answers3

40

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

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
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.

Mark B
  • 95,107
  • 10
  • 109
  • 188
-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;
M'vy
  • 5,696
  • 2
  • 30
  • 43
  • 1
    Shouldnt it be `base * a = new base()` ?? – Sid Apr 29 '13 at 23:23
  • 5
    Is this answer really relevant to the question? You didn't address `base b()` – narengi Jun 23 '15 at 02:38
  • 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? – Galaxy Nov 22 '19 at 06:04
  • You can see that at : https://stackoverflow.com/a/620402/637404 – M'vy Nov 22 '19 at 11:17