badmaash
badmaash

Reputation: 4845

what happens when i only call a constructor?

This may sound naive. I want to know what happens when i explicitly call a constructor like this:

class A{
/*...*/
  public:
    A(){}
};
int main(){
  A();
  return 0;
}

Is a useless object created which remains in the memory until the scope of main() ends?

Upvotes: 2

Views: 153

Answers (5)

Viren
Viren

Reputation: 2171

Okay, I re-visited temporary and found that in the above example, it's actually a part of expression that is initializing an object. So yes, the scope ends at ;

Here:

When a temporary object is created to initialize a reference variable, the name of the temporary object has the same scope as that of the reference variable. When a temporary object is created during the evaluation of a full-expression (an expression that is not a subexpression of another expression), it is destroyed as the last step in its evaluation that lexically contains the point where it was created.

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 791779

Strictly speaking you can never make a direct call to a constructor in C++. A constructor is called by the implementation when you cause an object of class type to be instantiated.

The statement A(); is an expression statement and the expression is a degenerate form of an explicit type conversion (functional notation). A refers to the type, strictly speaking constructors don't have names.

From the standard (5.2.3 [expr.type.conv] / 2:

The expression T(), where T is a simple-type-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized [...].

Because your class type has a user-declared default constructor the value-initialization of this temporary will use this constructor. (see 8.5 [dcl.init]/5)

Upvotes: 1

iammilind
iammilind

Reputation: 69988

when i explicitly call a constructor like this

You are not calling a constructor here; but creating a temporary object which gets destructed immediately. Constructor can be called explicitly with an object of that type (which is not advisable).

Is a useless object created which remains in the memory until the scope of main() ends?

It doesn't have scope till the function ends, but till the ; ends.

Upvotes: 2

Sophy Pal
Sophy Pal

Reputation: 435

Its considered a nameless temporary which gets destroyed after the end of the full expression. In this case, the point right after the semicolon. To prove this, create a destructor with a print statement.

Upvotes: 2

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You create an object that lasts until the end of the statement.

Upvotes: 3

Related Questions