简体   繁体   中英

No error for not initializing reference variable of class

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

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).

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM