I added a copy constructor and altered the delete statements. The following code compiles and runs as expected without errors; However, read the output below.
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
using namespace System;
class MMsg {
private:
char* m_message;
public:
//base constructor
MMsg(const char* message = "this is the default message"){
cout << "base constructor called" << endl;
m_message = new char[strlen(message) + 1];
strcpy(m_message, message);
}
//copy constructor
MMsg(const MMsg& copy) {
cout << "copy constructor called" << endl;
delete[] m_message;
cout << "copy constructor called" << endl;
m_message = new char[strlen(copy.m_message) + 1];
strcpy(m_message, copy.m_message);
}
~MMsg() {
delete[] m_message;
}
void show_message(){
cout << m_message << endl;
}
MMsg& operator=(const MMsg& msg){
cout << "assignment operator called" << endl;
if(this == &msg)
return *this;
delete[] m_message;
m_message = new char[strlen(msg.m_message)+1];
strcpy(this->m_message, msg.m_message);
return *this;
}
void change_message(char* msg){
delete[] m_message;
m_message = new char[strlen(msg) + 1];
strcpy(m_message, msg);
}
};
int main(array<System::String ^> ^args)
{
MMsg msg1("It's beginning to look alot like Christmas");
msg1.show_message();
//MMsg msg2 = msg1;
MMsg msg2;
msg2.show_message();
msg2 = msg1;
msg1.change_message("Night of the living dead");
msg1.show_message();
msg2.show_message();
return 0;
}
|
the following output is produced:
base constructor called
It's beginning to look alot like Christmas
base constructor called
this is the default message
assignment operator called
Night of the living dead
It's beginning to look alot like Christmas
//end output
But if I use:
instead of
1 2
|
MMsg msg2;
msg2 = msg1;
|
I get the following output and the program abruptly terminates:
base constructor called
It's beginning to look alot like Christmas
copy constructor called
//end output
I ran a debug and when it gets to this line:
msg2.m_message contains garbage instead of the default message it should contain when the base constructor was called.