I was wondering what is happening internally when assigning an anonymous object temporary to a named object:
#include <iostream>
class Object {
public:
Object (void) {
this->PrintAddress();
}
Object (const Object& another_object) {
std::cout << "Copy constructor is called!\n";
}
~Object (void) noexcept {}
void PrintAddress (void) const {
std::cout << "Object Address: " << this << '\n';
}
};
int main (int arg_count, char* arg_vector[]) {
// The following line:
Object object = Object();
object.PrintAddress();
return 0;
}
Compiling and executing the resulting binary shows that the copy constructor is not called and both the named object ('object') and the RHS temporary have the same address meaning they are the same object. I somehow feel like the compiler associates the temporary to the name hence why no constructor is executed (besides when creating the RHS temporary). To better see this, take a look at the following:
Object object (Object()); // Line 1
object.PrintAddress() // Line 2
Notice that although line 1 has the same syntax as an object that performs a copy constructor, it also has a syntax resembling a function pointer. Commenting Line 2 doesn't affect the ability of the program to compile and yet uncommenting Line 2 (assuming I just created an Object named object) yield a compile error (likely due to the fact that you cannot execute member functions on a function pointer).
Sorry if this has dragged on for too long, but what is happening internally when you do this?
Thank you for your time!