Assignment 5

Object-oriented techniques in C++

Goals

To understand access control, inheritance and functional polymorphism (late binding) in C++.

Procedure

Consider the following class definition and answer the questions following it.

class Employee {
private:
  string name;
public:
  void showName()
     { cout << name << endl; } // prints name on standard output
  string getName() { return name; }
};

1

In the context of the declaration:

Employee e;

which of the following are valid and which are invalid? Your answers should explain what is going on, especially in the case of the invalid ones.

a.  e.name = "Luis";

b.      e.showName();

c.       Employee::name = "Fred";

d.      string::name = "Sally";

e.       cout << Employee.getName() << endl;

f.        cout << e.getName() << endl;

2

To the class Employee, add the following declarations:

enum Range {Soprano, Alto, Tenor, Bass};

class Singer : public Employee {
private:
  Range r;
public:
  Range getRange() { return r; }
};

 

In the context of the declarations:

      Employee ceo;
      Singer tech1;

which of the following are valid and which are invalid? Your answers should explain what is going on, especially in the case of the invalid ones.

a.       ceo = tech1;
if (ceo.getRange() == Alto) ...

b.      tech1 = ceo;
if (tech1.getRange() == Alto) ...

c.       Employee *pe = &tech1;

d.    Singer *ps = &ceo;

e.       Singer *ps = (Singer *)&ceo;
ps->showName();
ps->getRange();

     

3

To the declarations for Employee and Singer add:

enum Medium {WaterColor, Oils, Pastel};
class Artist : public Employee {
private:
  Medium m;
public:
  void support() { ... }
};

  void support() { ... } // added to class Singer in public section

  virtual void support()=0; // added to class Employee in public section

Which of the following are valid and which are invalid? Your answers should explain what is going on, especially in the case of the invalid ones.

a.  Employee e;

b.      Artist a;

c.       Singer s;

d.      Employee *pe = &a;
pe->support();

e.       Artist *pa = (Singer *)&s;

f.        Artist *pa = &a;
pa->support();

 

Grading

This assignment is worth 50 points. Part 1 is worth 18 points, part 2, 14 points and part 3, 18 points..

Due Date

By April 28th 5:00 PM.