why constructor don't have return type

Recommended Answers

All 3 Replies

Here you go, in order to find that, I simply copied and pasted your question into google, and recieved that result.

I am amazed that people don’t even try to Google for an answer. Most of the time the first page has the answer and so much more.

In truth, the return value of a constructor is the object itself, or a temporary reference to an object that will soon disappear. Whether it is assigned to a variable, or a copy (via reference) is, depends upon whether or not it is used in the declaration of the variable, or in a simple assignment operator. Here is an example:

class foo
    int m_bar;
    foo(int aBar = 0 ) : m_bar(aBar) {}

int main(void)  // I seem to use this pattern a lot! :-)
    foo aFoo0;      // Constructed with default value of 0, m_bar == 0
    foo aFoo1(1);   // Constructs foo with m_bar == 1
    foo aFoo2 = 2;  // Operates like the previous, but m_bar == 2
    foo aFoo3 = foo(3); // Copies foo(3) to aFoo3, treating foo(3) as a reference, m_bar == 3
    foo& aFooRef = aFoo3;   // A reference to aFoo3, m_bar == 3

    // Now, assignment from a temporary reference
    aFoo0 = foo(4);     // aFoo0.m_bar now == 4 since foo(4) (as a reference) was copied to aFoo0.
    aFoo0 = aFooRef;    // aFoo0.m_bar now == 3 since aFoo3 is now copied to aFoo0.
    return 0;

I'm sure you are confused now, right! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.