Vijay
Vijay

Reputation: 67211

calling the default constructor

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!

Upvotes: 27

Views: 43009

Answers (3)

M&#39;vy
M&#39;vy

Reputation: 5774

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;

Upvotes: -6

Mark B
Mark B

Reputation: 96241

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.

Upvotes: 23

Bo Persson
Bo Persson

Reputation: 92231

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

Upvotes: 42

Related Questions