PDA

View Full Version : Question about initializing an object without assigning...



Zingam
3rd July 2013, 22:29
int main(...) {
.....
Application app(argc, argv);
new ApplicationUI(&app);
.....
}

I have seen a code like the above a few times but I don't understand why is it valid. Where does the initalized object go?

wysota
3rd July 2013, 22:49
It doesn't "go" anywhere, it is on a heap like any other object allocated with "new", it is just not assigned to any public variable.

Zingam
4th July 2013, 09:59
And what would be a good use case for initializing an object that I cannot access through I variable?
I'd like to fill this hole in my C++ knowledge but I cannot figure it out yet.

wysota
4th July 2013, 10:32
C++ has nothing to do with this. You don't need to assign the return value of new to be able to use the object. For instance the object might "install" itself on some other object in its constructor or you might simply not care to access the object directly in your app.

jonthom
21st August 2013, 21:14
C++ has nothing to do with this. You don't need to assign the return value of new to be able to use the object. For instance the object might "install" itself on some other object in its constructor or you might simply not care to access the object directly in your app.

wysota is technically correct. However, both of these uses would generally be considered bad style and potentially dangerous. If you see a memory allocation like that, it is most likely a memory leak. Again, though, in this specific example, the ApplicationUI probably 'imprints' itself into the given Application object.