Hello,
When I run the program it reproduces exactly the same output as in the book but before the console closes, I get corrupted heap error. Can anyone tell me why?
Here is my code:
Code:
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
class CMessage
{
private:
char* pmessage; // Pointer to object text string
public:
// Function to display a message
void ShowIt() const
{
cout << endl << pmessage;
}
////////////////////////////////////
// Function to reset a message to *
void reset()
{
char* temp = pmessage;
while( *temp )
*( temp++ ) = '*';
}
///////////////////////////////////////
// Overloaded assignment operator for CMessge objects
CMessage& operator =( const CMessage& aMess )
{
if( this == &aMess ) // check addresses, if equal return the 1st operand
return *this;
// Release memory for 1st operand
delete[] pmessage;
pmessage = new char[strlen( aMess.pmessage + 1 )];
// copy 2nd operand string to 1st
strcpy_s( this->pmessage, strlen( aMess.pmessage ) + 1, aMess.pmessage );
// return a reference to 1st operand
return *this;
}
///////////////////////////////////////////////
// Constructor definition
CMessage( const char* text = "Default message")
{
pmessage = new char[strlen( text ) + 1]; // Allocate space for text
strcpy_s( pmessage, strlen( text ) + 1, text ); // copy text to a new memory
}
/////////////////////////////////////////////////
// Copy constructor definition
CMessage( const CMessage& aMess )
{
size_t len = strlen( aMess.pmessage ) + 1;
pmessage = new char[len];
strcpy_s( pmessage, len, aMess.pmessage );
}
////////////////////////////////////////////////
// Destructor t free memory allocated by new
~CMessage()
{
cout << "Destructor called." // just to track what happens
<< endl;
delete[] pmessage; // Free memory assigned to pointer
}
};
int main ( void )
{
CMessage motto1( "The God is almighty ever!" );
CMessage motto2;
cout << "motto2 contains - ";
motto2.ShowIt();
cout << endl;
motto2 = motto1; // using new assignment operator
cout << "motto2 contains - ";
motto2.ShowIt();
cout << endl;
motto1.reset(); // Setting motto1 to * doesn't
// affect motto2
cout << "motto1 now contains - ";
motto1.ShowIt();
cout << endl;
cout << "motto2 still contains - ";
motto2.ShowIt();
cout << endl;
std::cin.get();
return 0;
}