Monday, December 12, 2011

[Cpp-Programming] Inheritance and termination housekeeping

// Base class declaration
class CEmployee
{
public:
CEmployee(char* f, char* l, int salary);
CEmployee(int s);
~CEmployee(void);
int getSalary();

int age;

protected:
char* fname;
char* lname;
int salary;
};


// Derived class declaration
class CEmpManager : public CEmployee
{
public:
CEmpManager(int age, int s);
CEmpManager(int age, char* f, char* l, int s);
int getAge();

~CEmpManager(void);


private:
int salary;
};


// CLASS DEFINITIONS

// CEmployee is base class
CEmployee::CEmployee( char* f, char* l, int s)
{
fname = new char [25];
lname = new char [25];
strcpy(fname, f);
strcpy(lname, l);
salary = s;
}
CEmployee::CEmployee(int s)
{
salary = s;

}
CEmployee::~CEmployee(void)
{
if(!IsBadStringPtr(fname, 25))
{
delete [] fname;
delete [] lname;
}
}
int CEmployee::getSalary()
{
return salary;
}


// CEmpManager is derived class, i.e, inherits from CEmployee above
CEmpManager::CEmpManager(int a, int s) : CEmployee(s)
{
salary = s;
age = a;
}
CEmpManager::CEmpManager(int a, char* f, char* l, int s) :
CEmployee(f, l, s)
{
salary = s;
age = a;
}
CEmpManager::~CEmpManager(void)
{
}
int CEmpManager::getAge()
{
return age;
}


void main(void)
{
// Start instantiating objects
CEmployee emp("Joe", "Black", 2000);

cout << "Employee salary: " << emp.getSalary() << endl;

CEmpManager man(45, 555);
CEmpManager man2(50, "Foo", "Bar", 56000);

cout << "Manager salary: " << man.getSalary() << endl;

cout << "Manager2 salary: " << man2.getSalary()
<< " Age: " << man2.getAge() << endl;
}


emp object uses dynamic memory. man object does not use dynamic
memory. man2 uses dynamic memory allocation. All three, emp, man, and
man2 will call:

CEmployee::~CEmployee(void)
{
if(!IsBadStringPtr(fname, 25))
{
delete [] fname;
delete [] lname;
}
}

man object will cause program to crash because it does not use
dynamic
memory. To protect against this crash, I have used infamous
IsBadStringPtr. How can this program be structured to resolve this
problem?


--
You received this message because you are subscribed to the Google Groups "C++ Programming" group.
To post to this group, send email to cpp-programming@googlegroups.com.
To unsubscribe from this group, send email to cpp-programming+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/cpp-programming?hl=en.

0 Comments:

Post a Comment

<< Home