Explore BrainMass

How are Derived Classes and Base Classes Related?

This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

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

1. What is wrong with the following code?

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

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
int wingSpan;
int eggSize;
int airSpeed;
int altitude;
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
int m_anInt;
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.

© BrainMass Inc. brainmass.com March 22, 2019, 1:58 am ad1c9bdddf

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
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.