I couldn't really think of a specific title, as I don't really know how to word it. I'm really confused on this, as my previous question did not really get answered, but only make me more confused. My other question asked
Setting std::string to 0 during definition vs setting std::string to 0
User mnciitbhu said that he was getting an error on GCC 5.2. I am using Microsoft Visual Studio so I tried it on Code::Blocks, and there were no errors. Besides that, I wanted to try this out for myself. I have a class - Test
class Test {
public:
Test(const Test& T) {
std::cout << "COPY CTOR\n";
}
Test(){
std::cout << "DEFAULT CTOR\n";
}
Test(int NUMBER) {
std::cout << "INT CTOR CALLED\n";
}
};
Inside my main function, when I do
Test t1 = 5;
t1 = 10;
the output is
INT CTOR CALLED
INT CTOR CALLED
Now where I am getting confused is when you do Test t1 = 5
, a user on the other question said it will create a temporary Test
, then call the copy constructor. This never calls the copy constructor. Also, in reference to my other question; when I did
// text = std::string
text = NULL;
one of the answers said that it didn't work because it did not define operator=
. My Test
class never defined it either, but doing
t1 = 10;
still works and calls the constructor again. One of the users on the other question said that in this context, it call the assignment operator. This did not, as you can tell from the output. So could someone please explain, in great detail, why
std::string text = NULL;
text = NULL;
gives me an error, and
Test t1 = 5;
t1 = 10;
works, and doesn't call the copy constructor, and calls the constructor twice.
What is the =
actually doing? Why does it call the constructor when I do t1 = 10