Unexpected destructor call

Jun 1, 2013 at 8:15pm
I am trying to get a handle on working with classes and wrote a simple class that is used to store and display a string. I wrote an operator function to overload the assignment operator so that one object of the class can be assigned to another:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstring>

using std::cout;

class CMessage
{
	private:
		char* pmessage;

	public:
		void ShowIt(void) const
		{
			cout << this->pmessage << "\n";
			return;
		}

		CMessage(const char* text = "Default message.")
		{
			this->pmessage = new char[strlen(text) + 1];
			strcpy_s(pmessage, strlen(text) + 1, text);
		}

		~CMessage()
		{
			cout << "Destructor called.\n";
			delete [] pmessage;
		}

		CMessage& operator = (const CMessage& aMessage)
		{
			if(this == &aMessage)
				return *this;

			delete [] pmessage;		
			this->pmessage = new char[strlen(aMessage.pmessage) + 1];
			strcpy_s(pmessage, strlen(aMessage.pmessage) + 1, aMessage.pmessage);
			return *this;
		}

};

int main(void)
{
	CMessage obj1;
	obj1.ShowIt();
	obj1 = "Lets see if this works.";
	obj1.ShowIt();

	return 0;
}


When I try to assign a string to an object directly the operator member function is used, but there is also a call to the destructor that I don't understand:


Default message.
Destructor called.
Lets see if this works.
Destructor called.


The first call of the destructor eludes me. When I overload the assignment operator to handle the assignment of a string correctly, there is only one call to the destructor. Can someone explain to me how the statement obj1 = "Lets see if this works."; is interpreted so as to solicit a call of the destructor?
Jun 1, 2013 at 8:21pm
1) implicit conversion due to constructor CMessage(const char* text) is performed. Temporary object is created.
2) obj1 assigned value of temporary object using operator=.
3) Temporary object is destroyed.

Note that compiler would probably optimize avay much of the code if not for output statement in destructor.
Jun 1, 2013 at 8:49pm
Thank you for your quick reply. You are right, if I declare the constructor explicit my compiler flags the implicit conversion. Thank you for your help, i'll mark my question as solved.
Topic archived. No new replies allowed.