Hi everyone,
I'm trying to create a Name class that holds the name and the surname of a person.
Name.h
Code:
#ifndef Name_h
#define Name_h
class Name
{
public:
Name(Name& nm);
Name(char* n = "nothing" ,char* sn = "nothing");
~Name(void);
void Setname(char* n);
void Setsname(char* sn);
char* Getname(void);
char* Getsname(void);
void Print(void);
Name& operator =(Name& nm);
private:
char* name; // name
char* sname; // surname
};
#endif
Name.cpp
Code:
#include "Name.h"
#include <cstring>
#include <iostream>
using namespace std;
Name::Name(char* n ,char* sn)
{
cout << "Constructor Called!" << endl;
name = new char[strlen(n)+1];
sname = new char[strlen(n)+1];
strcpy(name, n);
strcpy(sname, sn);
}
Name::~Name(void)
{
cout << "Destructor Called!" << endl;
delete name;
delete sname;
}
Name::Name(Name& nm)
{
cout << "Copy Constructor called" << endl;
this->name = new char[strlen(nm.Getname()) + 1];
this->sname = new char[strlen(nm.Getsname())+1];
strcpy(name, nm.Getname());
strcpy(sname, nm.Getsname());
}
void Name::Print(void)
{
cout << " Name = " << name << endl
<< "Surname = " << sname << endl;
}
void Name::Setname(char* n)
{
delete name;
name = new char[strlen(n) + 1];
strcpy(name, n);
}
void Name::Setsname(char* sn)
{
delete sname;
sname = new char[strlen(sn) + 1];
strcpy(sname, sn);
}
char* Name::Getname(void)
{
return name;
}
char* Name::Getsname(void)
{
return sname;
}
//==============================================================================
Name& Name::operator =(Name& nm)
{
delete this->name;
delete this->sname;
this->name = new char[strlen(nm.Getname()) + 1];
this->sname = new char[strlen(nm.Getsname())+1];
strcpy(name, nm.Getname());
strcpy(sname, nm.Getsname());
return *this;
}
main.cpp
Code:
#include <iostream>
#include "Name.h"
using namespace std;
int main(void)
{
Name Obj1;
Obj1.Setname("Abc");
Obj1.Setsname("Defghi");
Obj1.Print();
Name Obj2(Obj1);
Obj2.Print();
Obj1.Print();
Obj1.~Name();
Obj2.Print();
Name Obj3;
Obj3 = Obj2;
Obj3.Print();
cin.get();
return 0;
}
It runs in Dev-C++ with no errors but in VS Studio 2005 it runs, shows me the results normally, i press enter to close the window and at that time it shows me a message "debug assertion failed..."
Can you please help me? I have no idea what to do...