2

In most of the c++ code that i have studied, there is no return statement in the copy constructor function, yet this one must return an object. I want to understand why?

Ali
  • 56,466
  • 29
  • 168
  • 265
WildThing
  • 665
  • 2
  • 9
  • 17
  • 8
    Constructors cannot return values. – chris Aug 08 '13 at 10:02
  • 1
    What about default constructors? Do they have a return value? – Luchian Grigore Aug 08 '13 at 10:03
  • 1
    What do you mean by 'this one'? – The Forest And The Trees Aug 08 '13 at 10:04
  • @chris what about the = operator? – WildThing Aug 08 '13 at 10:05
  • @WildThing, Not the same, but that does. – chris Aug 08 '13 at 10:06
  • 1
    @WildThing Copy assignment is not the same as copy construction. [E.g. see here](http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/). – BoBTFish Aug 08 '13 at 10:06
  • 1
    I've coded C++ for 25 years and taken things for granted with regard to this. Never thought of why constructors don't return themselves so to say. Think it is a good question. Everybody with C++ knowledge knows that a constructor does not return a value, but what would be wrong with some kind of return syntax-wise. I think that is interesting and therefore I think it is a good question. –  Aug 08 '13 at 10:15
  • *"In most of the c++ code that I have studied, there is no return statement in the copy constructor function"* - Not *"most"*, all (well, except if it was invalid code of course). – Christian Rau Aug 08 '13 at 11:37

2 Answers2

3

The constructors doesn't return a value, they are simply called as part of the object construction, and the actual "returning an object" is the job of the compiler and its generated code.

For example, lets say you have a class Foo, then when declaring a variable of that class

Foo myFoo;

the compiler creates the object for you, and calls the appropriate constructor

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

The default constructor doesn't return a value. It is simply called at the object construction.

From the standard :

12.1 Constructors [class.ctor]

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). An implicitly-declared default constructor is an inline public member of its class.

[....]

No return type (not even void) shall be specified for a constructor. A return statement in the body of a constructor shall not specify a return value. The address of a constructor shall not be taken.

Here is an example of use :

class Foo
{
public:
    Foo() {} // User defined default constructor
};
Foo myFoo;
Pierre Fourgeaud
  • 14,290
  • 1
  • 38
  • 62