user1013944
user1013944

Reputation:

It seems at a glance that a constructor return an object

There are many ways to initialize an object, one of which is calling a constructor of centain user-defined type. Here are the examples.

Hello my_hello = Hello(3);
Hello my_hello(3);

As you already know, a constructor doesn't return anything. However, as you look above, it seems that it does return its initialized object. Furthermore, the assignment operator makes it more suspicious because it means it copys the right-hand object to the left-hand object.

Am i guessing wrong? Would you please explain it?

Upvotes: 1

Views: 88

Answers (3)

Graham Griffiths
Graham Griffiths

Reputation: 2216

only one way to find out...try some code :

#include <iostream>
#include <cstdio>

using namespace std;

class Hello{
    public:
    Hello(int n)
    {
        printf("CTOR\n");
    }

    Hello& operator=(Hello& h)
    {
        printf("assignment\n");
        return *this;
    }
};

int main() {

    printf("first:\n");
    Hello firstHello(3);

    printf("\nsecond:\n");
    Hello secondHello = Hello(4);

    return 0;
}

result :

first:
CTOR

second:
CTOR

i.e. no assignment operator called. should really add a copy constructor and check that is used instead...consider it an exercise for the reader.

http://ideone.com/9Yr2WY

EDIT : out of curiosity, here is a version including a copy constructor. In this case neither of the lines calls the copy constructor - as Joachim points out, the compiler has succeeded in optimizing out the copy : http://ideone.com/wQ1VTK

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409482

The declaration

Hello my_hello = Hello(3);

creates two objects. First a temporary object from Hello(3), and this temporary object is then copied through the copy-constructor to my_hello followed by the destruction of the temporary object.

However, to further muddle up the water, this copying and destruction of the temporary object may actually not happen due to copy elision, a very common compiler optimization.

Upvotes: 3

Puppy
Puppy

Reputation: 147054

As you already know, a constructor doesn't return anything.

This is strictly true, per Standard.

However, it's an awful lot simpler to consider a constructor for T as a function returning a T (or emplacing it, a'la new and placement new). This is essentially how they're both used and implemented.

Also, there is no assignment operator in your code. That is copy-initialization, which is not the same thing. The my_hello object is copied from Hello(3).

Upvotes: 1

Related Questions