Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of constructing an object in C++

I want to construct an object in the stack, using C++. Do you know what is the difference between these to ways of calling the constructor (with and without parenthesis):

a) MyClass object ;

b) MyClass object() ;

I am using MFC and when constructing the global variable for the main app, if I use the latter way, I get an exception, I thought these two ways were equivalent.

Thank you guys for any information.

like image 431
lurks Avatar asked Feb 22 '10 03:02

lurks


People also ask

How are objects created in C?

In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects. To create an object of MyClass , specify the class name, followed by the object name.

What are the two main ways to instantiate an object?

Programmers can instantiate objects on the heap with a new keyword or on the stack as a variable declaration.


1 Answers

This is one of those gotchas of C++.

MyClass object();

is the way that a function prototype is defined in C++, so the compiler thinks you are trying to declare another function in the middle of another function.

If you want to invoke the default constructor (i.e. the one which takes no arguments), use this syntax instead:

MyClass object;

See also Garth Gilmour's answer to the now-deleted question What is your (least) favorite syntax gotcha?:

In C++

Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype
like image 160
LeopardSkinPillBoxHat Avatar answered Sep 28 '22 18:09

LeopardSkinPillBoxHat