Home > Blockchain >  Does constructor in cpp doesnot return anything?
Does constructor in cpp doesnot return anything?

Time:07-11

It is said that constructor doesnot return anything.But if constructor doesnot return anything, then how do this code segment works: *this=classname{args};. I hope someone could shed me some light on whats actually going under the hood.

A complete code:

#include <iostream>

using namespace std;

class hell {
private:
    int a{}, b{};
public:
    hell(int _a = 7, int _b = 8) : a{ _a }, b{ _b } {}

    void print() {
        cout << a << endl << b << endl;
    }

    void change() {
        *this = hell(4, 5);
    }
};

int main() {
    hell h;
    h.print();
    h.change();
    h.print();
    return 0;
}

CodePudding user response:

The statement

*this = hell(4, 6);

does two things:

  1. First it create a temporary and unnamed object of the class hell, initialized using the values you use to pass to a suitable constructor.

  2. Then that temporary and unnamed object is copy-assigned to the object pointed to by this.


It's somewhat similar to this:

{
    hell temporary_object(4, 5);  // Create a temporary object
    *this = temporary_object;  // Copy the temporary object to *this
}

CodePudding user response:

Your question must be about this line:

*this = hell(4,5);

This might look like a function call, calling the constructor function. But this is not a function call. This is (a particular) syntax for creating a new hell object, a temporary object. This is slightly outdated syntax, modern C prefers:

*this = hell{4, 5};

but it's the same thing.

This does call the constructor, but only as part of constructing a new object.

Once the temporary object gets constructed it gets assigned to *this. The End.

CodePudding user response:

For better intuition, constructor can be called "initializator". This reveals more of it's main purpose. The constructor initializes object rather then creates. So the instance of the object is already present in the memory when the constructor is called. All it does is initializing it.

  • Related