Inheritance/Polymorphism  «Prev  Next»
Lesson 4 A derived class
Objective Describe the General Syntax of a Derived Class and examine an Example

Describe General Syntax of Derived Class

A class can be derived from an existing class using the general form:
class class name:(public| protected| private) base class { 
     member declarations

Visibility of Inherited members

One aspect of the derived class is the visibility of its inherited members. The access specifier keywords public, protected, and private are used to specify how the base class members are to be accessible to the derived class. The new keyword protected specifies that a member is accessible to other member functions within its own class and any class immediately derived from the member function's class. When you declare a derived class without a base class access specifier, the derivation is considered private.
When a base class is declared private, its public and protected members are considered private members of the derived class, while private functions of the base class are inaccessible to any derived class.


Consider developing a class to represent students at a college or university:

enum year { fresh, soph, junior, senior, grad };

class student {
  student(char* nm, int id, double g, year x);
  void  print() const;
  int     student_id;
  double  gpa;
  year    y;
  char    name[30];

We could write a program that lets the registrar track such students. While the information stored in student objects is adequate for undergraduates, it omits crucial information needed to track graduate students.
Derived Class Benefits
Such additional information might include the graduate students' means of support, department affiliations, and thesis topics. Inheritance lets us derive a suitable grad_student class from the base class student as follows:

enum support { ta, ra, fellowship, other };
class grad_student : public student {
   (char* nm, int id, double g, year x, support t,
    char* d, char* th);
  void  print() const;
  support s;
  char dept[10];
  char thesis[80];