Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return type of the constructor in C++

I know that there is no return type of the constructors in C++

However, the code below compiles right. What is returned by the constructor in the code below?

class A{

public:
A() {}
}


A a = A();      //what is returned by A() here, why?

Is there any conflict here?

like image 494
skydoor Avatar asked Mar 06 '10 03:03

skydoor


People also ask

What is return type in constructor?

A constructor doesn't have any return type. The data type of the value retuned by a method may vary, return type of a method indicates this value. A constructor doesn't return any values explicitly, it returns the instance of the class to which it belongs.

Is constructors have return type?

Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.

Is constructor return type void?

Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created.

What is the return type of constructors int?

1. What is the return type of Constructors? Explanation: Constructors does not have any return type, not even void.


2 Answers

Nothing is returned from the constructor. The syntax A() is not a constructor call, it creates a temporary object of type A (and calls the constructor in the process).

You can't call a constructor directly, constructors are called as a part of object construction.

In your code, during the construction of the temporary the default constructor (the one you defined) is called. Then, during the construction of a, the copy constructor (generated automatically by the compiler) is called with the temporary as an argument.

As Greg correctly points out, in some circumstances (including this one), the compiler is allowed to avoid the copy-construction and default-construct a (the copy-constructor must be accessible however). I know of no compiler that wouldn't perform such optimization.

like image 179
avakar Avatar answered Oct 16 '22 07:10

avakar


The syntax T(), where T is some type, is a functional-cast notation that creates a value-initialized object of type T. This does not necessarily involve a constructor (it might or it might not). For example, the int() is a perfectly valid expression and type int has no constructors. In any case, even if type T has a constructor, to interpret T() as "something returned from constructor" is simply incorrect. This is not a constructor call.

like image 42
AnT Avatar answered Oct 16 '22 09:10

AnT