Question

I have reviewed many Q&A, but I cannot find a certain answer to this question.

For a class like this:

class A {
     public:
     int i;
     inline A() : i() {}
};

In plain C++98, how do I guarantee to call the default (argument-less) constructor at declaration in the most compact way?

A a;       //Is this guaranteed to call the default (argument-less) constructor?

A b();     //This is not what I want, the compiler thinks it's a function declaration
           //http://stackoverflow.com/a/877538/2436175

A c = A(); //This I know it works

(For what it is worth, I have tried it here, in this instance it worked but who knows which values were in the stack...)

Note: class A in the end will have to be more complicated of what shown in the example.

Was it helpful?

Solution

Line 1) calls the default constructor (or a constructor with all default parameters as Joachim stated)

Line 2) as you noted - not a constructor call

Line 3) a construction and an assignment - so default constructor and copy constructor will be called (unless the compiler optimizes the copy construction away). As pointed out in the comments - if (with C++11), a move constructor is available, this will be called.

OTHER TIPS

A a;       //Is this guaranteed to call the default constructor?

This is correct, it will call the default constructor (or a constructor with default values for all its arguments).

If you want to construct your objects like this you have to either provide a default constructor (constructor without parameters) or let the implementation synthesise one for you (for this to happen you cant define any constructor for your class).

Also, like others have stated in the comments, this will also work for PODs (plain old data structures).

For a struct to be considered POD it must not have virtual functions, base classes, non-static members that are private or protected, destructor or constructors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top