Purchase Solution

How are Derived Classes and Base Classes Related?

Not what you're looking for?

Ask Custom Question

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.

Purchase this Solution

Solution Summary

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

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

Purchase this Solution


Free BrainMass Quizzes
Basic Computer Terms

We use many basic terms like bit, pixel in our usual conversations about computers. Are we aware of what these mean? This little quiz is an attempt towards discovering that.

Word 2010: Table of Contents

Ever wondered where a Table of Contents in a Word document comes from? Maybe you need a refresher on the topic? This quiz will remind you of the keywords and options used when working with a T.O.C. in Word 2010.

Javscript Basics

Quiz on basics of javascript programming language.

C# variables and classes

This quiz contains questions about C# classes and variables.

Java loops

This quiz checks your knowledge of for and while loops in Java. For and while loops are essential building blocks for all Java programs. Having a solid understanding of these constructs is critical for success in programming Java.