Reputation: 2244
I am a newbie and have a basic doubt about relationship between object creation and constructors.
Program- 1
#include<iostream>
using namespace std;
class xxx{
private: int x;
public: xxx(){cout<<"constructer is called"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1; //Constructor is called
return 0;
}
Output- constructor is called
Program- 2
#include<iostream>
using namespace std;
class xxx{
private: int x;
public: xxx(){cout<<"constructer is called"<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1(); //Constructor xxx() is not called.
return 0;
}
Output- blank Any information is very helpfule
Upvotes: 1
Views: 76
Reputation: 23634
xxx x1;
creates an object of class xxx
, therefore, calls default constructor of class xxx
.
xxx x1();
declares a function that returns an object of class xxx
and function name is x1
, takes no parameter. It is not an instantiation of class xxx
, therefore, there is no constructor being called.
Upvotes: 2
Reputation: 121971
This:
xxx x1();
is a function declaration (function called x1
taking no arguments and returning an xxx
), not a variable declaration so no instance of xxx
is created (hence no constructor call).
Upvotes: 4