home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C++ for Dummies (3rd Edition)
/
C_FD.iso
/
CHAP22
/
CHAP22_1.CPP
Wrap
C/C++ Source or Header
|
1996-09-02
|
1KB
|
65 lines
// Chap22_1.cpp
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
class Name
{
public:
Name()
{
pName = (char*)0;
}
Name(char *pN)
{
copyName(pN);
}
Name(Name& s)
{
copyName(s.pName);
}
~Name()
{
deleteName();
}
//assignment operator
Name& operator=(Name& s)
{
//delete existing stuff...
deleteName();
//...before replacing with new stuff
copyName(s.pName);
//return reference to existing object
return *this;
}
protected:
void copyName(char *pN);
void deleteName();
char *pName;
};
//copyName() - allocate heap memory to store name
void Name::copyName(char *pN)
{
pName = (char*)malloc(strlen(pN) + 1);
if (pName)
{
strcpy(pName, pN);
}
}
//deleteName() - return heap memory
void Name::deleteName()
{
if (pName)
{
delete pName;
pName = 0;
}
}
int main()
{
Name s("Claudette");
Name t("temporary");
t = s; //this invokes the assignment operator
return 0;
}