Home » Learn C++ » Derived Classes

Derived Classes

Defining Derived Classes:

            The syntax for defining a derived class is slightly different from the syntax of the base class definition. The declaration of a derived class also includes the name of the base class from which it is derived.
The general syntax for defining a derived class is:

 
class sub_class_name : specifier base_class_name
{
———————–
members of derived class

———————–

};

 
where

 
sub_class_name represents name of the derived class.

: (colon) sets relation between the classes.
specifier represents the access specifier. It may be public, private or protected.
base_class_name represents name of the base class.

 
For example, a class “student” is defined as.

class student
{
private:
char name[l5], address[15];
public:
void input (void);
void show(void);

};

 

            The class student has two data members and two member functions. Suppose the marks obtained by a student in three different subjects and the total marks of these subjects are to be included as new data members in the above class. This is done by adding new members in the class. There are two ways in which these new members can be added to the class. These are:

  • Add new members in the original class.
  • Define a new class that has the new members and that also uses members of the existing “student” class. Using the members of an existing class is the principle of inheritance. The new class is the derived class. The existing class serves as the base class for the derived class.

 

            Driving a new class from the existing class reduces the size of the program. It also eliminates duplication of code within the program.

            For example, let the name of the new class be marks. This class uses the members of the existing student class.

class marks : public student
{
private:
int sl, s2, s3, total;
public:
void inputmarks (void);
void show_detail (void);

};

 

            The class marks is derived from the class student. The class marks is the derived class. The class student is the base class.

            The derived class marks has four data members of integer type and two member functions. It also uses the code of the base class student.

            The derived class cannot directly access the private data members of the base class student by using the dot operator. These members are only accessible to the derived class through the interface functions within the base class.

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.