Explore BrainMass
Share

How are Derived Classes and Base Classes Related?

This content was STOLEN 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
{
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.

© BrainMass Inc. brainmass.com October 25, 2018, 8:56 am ad1c9bdddf
https://brainmass.com/computer-science/programming-languages/how-are-derived-classes-and-base-classes-related-558184

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
See Also This Related BrainMass Solution

Re-usability in the Procedural and Object Oriented Languages

Re-usability is the ability to use code written for another situation. Most languages and programming paradigms support re-usability in some form. Create a report about re-usability in the procedural and object oriented languages. These two paradigms support re-usability in different ways. Document the differences in a Word document. In addition, list the pros and cons of re-usability for these paradigms.

View Full Posting Details