Share
Explore BrainMass

How are Derived Classes and Base Classes Related?

How are derived classes and base classes related in these exercises:

1. What is wrong with the following code?

class CBadClass
{
private:
int len;
char* p;
public:
CBadClass(const char* str): p(str), len(strlen(p)) {}
CBadClass(){}
};

2. Suppose you have a class CBird, as follows, that you want to use as a base class for deriving a hierarchy of bird classes:

class CBird
{
protected:
int wingSpan;
int eggSize;
int airSpeed;
int altitude;
public:
virtual void fl y() { altitude = 100; }
};

Is it reasonable to create a CHawk by deriving from CBird? How about a COstrich? Justify your answers. Derive an avian hierarchy that can cope with both of these birds. Any guidance will be good help.

3. Given the following class,

class CBase
{
protected:
int m_anInt;
public:
CBase(int n): m_anInt(n) { cout < < "Base constructor\n"; }
virtual void Print() const = 0;
};

what sort of class is CBase and why? Derive a class from CBase that sets its inherited integer value, m_anInt, when constructed, and prints it on request. Write a test program to verify that your class is correct.

Solution Preview

1. There are few obvious issues with the given code.

a. Order of members initialization in initialization list should be same as in their declaration in the class.

We could fix this issue in initialization list.

CBadClass(const char* str) : len(strlen(p)), p(str) {}

However this fix has its own issues. When initializing len with strlen(p), p is uninitialized (initialization happening left to right) and this is wrong (can lead to execution time program crash and/or undefined behavior).

So better fix would be to fix the order in members declaration.

class CBadClass
{
private:
char *p;
int ...

Solution Summary

Solution not only points out what is wrong with the code, but it also provides solution to fix it well.

$2.19