Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between creating object with () or without

Tags:

i just run into the problem

error: request for member ‘show’ in ‘myWindow’, which is of non-class type ‘MainGUIWindow()’ 

when trying to compile a simple qt-application:

#include <QApplication> #include "gui/MainGUIWindow.h"   int main( int argc, char** argv ) {   QApplication app( argc, argv );     MainGUIWindow myWindow();   myWindow.show();     return app.exec(); } 

I solved this by replacing

MainGUIWindow myWindow();  

by

MainGUIWindow myWindow; 

but I don't understand the difference. My question: What is the difference?

Regards, Dirk

like image 942
Dirk Avatar asked Feb 25 '11 11:02

Dirk


People also ask

What happens if we create an object with new and without new?

In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object. This will be stored at the stack section. This will be destroyed when the scope ends.

What happens when we create an object in C++?

When a C++ object is created, two events occur: Storage is allocated for the object. The constructor is called to initialize that storage.

What is the difference between new in C++?

Use new: Call operator new function to get dynamic memory, and then to call the constuctor function. Not use new: Will not call operator new function, just directly to call the constuctor function. The stack will be used directly, no use to malloc.


2 Answers

The other answers correctly state that the parentheses version is actually a function declaration. To understand it intuitively, suppose you wrote MainGUIWindow f(); Looks more like a function, doesn't it? :) The more interesting question is what is the difference between

MainGUIWindow* p = new MainGUIWindow; 

and

MainGUIWindow* p = new MainGUIWindow(); 

The version with parentheses is called value-initialization, whereas the version without is called default-initialization. For non-POD classes there is no difference between the two. For POD-structs, however, value-initialization involves setting all members to 0,

my2c

Addition: In general, if some syntactic construct can be interpreted both as a declaration and something else, the compiler always resolves the ambiguity in favor of the declaration.

like image 117
Armen Tsirunyan Avatar answered Jan 26 '23 00:01

Armen Tsirunyan


The following:

MainGUIWindow myWindow(); 

declares a function that takes no arguments and returns MainGUIWindow. I.e. myWindow is a function name.

MainGUIWindow myWindow; 

on the other hand creates an object myWindow of type MainGUIWindow.

like image 36
Maxim Egorushkin Avatar answered Jan 25 '23 23:01

Maxim Egorushkin