Code:class test
{
public:
test()
};
void main()
{
test t = test(); // what is returned here?
}
Since constructor do not have return type. Then what is returned in t?
Printable View
Code:class test
{
public:
test()
};
void main()
{
test t = test(); // what is returned here?
}
Since constructor do not have return type. Then what is returned in t?
When you write
two things are happening:Code:test t = test();
1) test() creates a temporary of type test.
2) The test t = part creates a second instance of type test. This instance t is created via the class's copy constructor (test t = test(); is basically the same as test t( test() );). The argument for t's copy constructor is the temporary created in step 1.
EDIT: Note that in your case, just test t; would be sufficient. This would create instance t via test's default constructor.
EDIT #2: In C++ and C, it should always be int main(), not void main().
I didn't understand this point.Quote:
is basically the same as test t( test() );
In my opnion it should be
test t(t); // This syntax is incorrect. because you cannot pass same object in constructor; But I thought default copy constructor would require this.
Please clarify.
A copy constructor requires as its argument another instance of the same type. The expression test() generates a temporary that satisfies that requirement.
Trying playing around with this program a bit.
Compile without optimizations.Code:#include <iostream>
class test
{
public:
test()
{
std::cout << "Creating test instance at 0x" << std::hex << this << std::dec << " via default c'tor.\n";
}
~test()
{
std::cout << "Destroying test instance at 0x" << std::hex << this << std::dec << ".\n";
}
test( const test& t )
{
std::cout << "Creating test instance at 0x" << std::hex << this << std::dec << " via copy c'tor. Address of source instance is 0x"
<< std::hex << &t << std::dec << ".\n";
}
test& operator = ( const test& t )
{
std::cout << "Copy assigning to test instance at 0x" << std::hex << this << std::dec << ". Address of source instance is 0x"
<< std::hex << &t << std::dec << ".\n";
return *this;
}
};
int main()
{
test t = test();
t = test();
}
P.S. The program might actually not use the copy constructor at all. This is because your compiler is allowed to remove the copy if it finds that it is unnecessary. This is called copy elision: http://en.wikipedia.org/wiki/Copy_elision
Output:
I don't know why copy constructor is not called?Code:Creating test instance at 0x002AF7FB via default c'tor.
Destroying test instance at 0x002AF7FB.
Press any key to continue . . .
You may have missed antred's postscript:Quote:
Originally Posted by freiza
Quote:
Originally Posted by antred