I am a first grade student and this is my first time asking in stackoverflow.Recently my professor sent me a piece of code asking me to find out what was wrong with it.
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
A(int c);
~A();
int code;
char *name;
};
A::A(int c)
{
code = c;
name = new char[50];
if(name == 0)
{
cout << "Unavailable memory" << endl;
exit(1);
}
}
A::~A()
{
cout << "Delete pointer to " << name << endl;
delete [] name;
}
int main(void)
{
A a1(100), a2(200);
strcpy(a1.name, "Mike");
a2 = a1;
strcpy(a2.name, "Peter");
cout << a1.name << endl;
return 0;
}
As far as i know,the program should crash after the destructor of object a2 is called because the destructor of object a1 will try to delete the same already deleted memory.After this line:
a2 = a1;
the char* of object a2 points at the same address that the pointer of object a1 points,thus creating a mess upon calling the destructor.What really doesn't make sense to me is the fact that the program runs perfectly fine right now without any crashes,however yesterday the program crashed with the following output on console:
Delete pointer to Peter
Delete pointer to [insert strange characters here]
Process exited with return value 344233377
So im asking if someone could enlighten me regarding the strange behaviour of this program.BTW is it better to use operator overloading like this
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
A(int c);
~A();
A operator=(A a1);
int code;
char *name;
};
A::A(int c)
{
code = c;
name = new char[50];
if(name == 0)
{
cout << "Unavailable memory" << endl;
exit(1);
}
}
A::~A()
{
cout << "Delete pointer to " << name << endl;
delete [] name;
}
A A::operator=(A a1)
{
*name=*a1.name;
code=a1.code;
return *this;
}
int main()
{
A a1(100), a2(200);
strcpy(a1.name, "Mike");
a2 = a1;
strcpy(a2.name, "Peter");
cout << a1.name << endl;
return 0;
}
or should i use something like a copy constructor?
Aucun commentaire:
Enregistrer un commentaire