Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Sunday, September 29, 2024

Inheritance Fundamentals and Base-Class Access Control

Inheritance Fundamentals and Base-Class Access Control

 

Learning Objectives

After completing this module, students should be able to:

•      Explain inheritance and the is-a relationship, and use the terms base class and derived class.

•      Write derived classes using single, multilevel, multiple, hierarchical and hybrid inheritance.

•      Predict the access of inherited members under public, protected and private inheritance.

•      Explain which conversions between derived and base classes are allowed, and why name hiding occurs.

•      Describe what a derived object contains and what is not inherited.

 

Important: Programs of this unit were compiled with g++ -std=c++17 -Wall -Wextra and the output shown is the real output. Some programs use default member initializers (for example int a = 10; inside a class) and the keyword override; both need C++11 or later. Where a feature depends on the C++ version, a Version Note box says so.

 

1. Introduction to Inheritance

Definition: Inheritance is the mechanism by which a new class, the derived class (child or subclass), acquires the members of an existing class, the base class (parent or superclass), and can add to them or change their behaviour.

 

Real objects form natural hierarchies: a student, a teacher and a staff member are all persons; a car and a bike are vehicles. The data and functions common to a person (name, age, display) should be written once, in a Person class, and reused by the more specific classes. This is the purpose of inheritance.

Term

Meaning

Example

Base class

The class whose members are inherited

Person

Derived class

The class that inherits; it extends or specialises the base

Student

Is-a relationship

A derived object is a base object of a more specific kind

A Student is a Person

Overriding

A derived class gives its own version of an inherited function

Module 5

Generalization / specialization

Moving up towards the common base / down to a more specific class

Student → Person

 

1.1 Advantages

1.      Code reuse: common members are written once in the base class.

2.      Less duplication and easier maintenance: a correction in the base class benefits every derived class.

3.      Extensibility: a new class can be built on a tested class without changing it.

4.      Natural modelling of real hierarchies.

5.      Basis for polymorphism (Modules 5–7): a base-class pointer can refer to objects of derived classes.

 

Note: Inheritance expresses is-a. If the relationship is has-a (a Car has an Engine), use a data member (composition) instead of inheritance.

 

2. Defining a Derived Class

class DerivedClass : access_specifier BaseClass

{

    // members of the derived class

};

 

The access specifier (public, protected or private) controls how the inherited members are seen through the derived class (Section 4). If it is omitted, it is private for a class and public for a struct.

Program 1.1: A Student class derived from Person.

#include <iostream>

#include <string>

using namespace std;

 

class Person {

public:

    string name;

    int age;

 

    void displayPerson() const

    {

        cout << "Name: " << name << "\n";

        cout << "Age: " << age << "\n";

    }

};

 

class Student : public Person {

public:

    int enrollmentNumber;

 

    void displayStudent() const

    {

        displayPerson();                       // inherited member function

        cout << "Enrollment Number: " << enrollmentNumber << "\n";

    }

};

 

int main()

{

    Student s;

    s.name = "Rahul Sharma";                   // inherited data members

    s.age = 20;

    s.enrollmentNumber = 101;

    s.displayStudent();

    return 0;

}

 

Output:

Name: Rahul Sharma

Age: 20

Enrollment Number: 101

 

Title: Person is the base class and Student is derived from it by public inheritance. - Description: Person is the base class and Student is derived from it by public inheritance.

Figure 1.1: Person is the base class and Student is derived from it by public inheritance.

1.      class Student : public Person makes Student a derived class of Person.

2.      The object s of type Student has the members name and age (inherited) and enrollmentNumber (its own); it can call displayPerson() directly, and displayStudent() calls it as well.

3.      The base class knows nothing about Student: inheritance is a one-way relationship from derived to base.

 

2.1 What a derived object contains

A derived object contains a complete base-class subobject followed by the members declared in the derived class. Creating a Student therefore creates the Person part as well (Module 3 explains how it is constructed).

Title: Layout of a Student object: the Person part comes first. - Description: Layout of a Student object: the Person part comes first.

Figure 1.2: Layout of a Student object: the Person part comes first.

Program 1.2: Sizes and the position of the base part.

#include <iostream>

#include <string>

using namespace std;

 

class Base {

public:

    int a;

    int b;

};

 

class Derived : public Base {

public:

    int c;

};

 

int main()

{

    Derived d;

    d.a = 1; d.b = 2; d.c = 3;

    // the Base part starts at the same address

    Base *bp = &d;

    cout << "sizeof(Base)    = " << sizeof(Base) << endl;

    cout << "sizeof(Derived) = " << sizeof(Derived) << endl;

    cout << "Base part at start of object: " << boolalpha

         << (static_cast<void *>(bp) == static_cast<void *>(&d)) << endl;

    return 0;

}

 

Output:

sizeof(Base)    = 8

sizeof(Derived) = 12

Base part at start of object: true

 

Derived adds one int to the two int members of Base, so its size is larger by the size of an int. The sizes are implementation-specific (compilers may add padding); only the order – base part first – is typical.

3. Types of Inheritance

Type

Description

Example

Single

One derived class from one base class

class B : public A

Multilevel

A class derived from a derived class (a chain)

class C : public B, class B : public A

Multiple

A class with two or more direct base classes (Module 2)

class C : public A, public B

Hierarchical

Several classes derived from one base class

Student and Teacher from Person

Hybrid

A combination of the above; often a diamond (Module 4)

Two classes from one base, then one class from both

 

Title: Types of inheritance (arrows point from the derived class to its base class). - Description: Types of inheritance (arrows point from the derived class to its base class).

Figure 1.3: Types of inheritance (arrows point from the derived class to its base class).

Program 1.3: Single, multilevel, multiple and hierarchical inheritance.

#include <iostream>

using namespace std;

 

/* 1. Single inheritance */

class A { public: void showA() const { cout << "A" << endl; } };

class B : public A { public: void showB() const { cout << "B" << endl; } };

 

/* 2. Multilevel inheritance: Person -> Student -> ResearchStudent */

class Person { public: void role() const { cout << "Person" << endl; } };

class Student : public Person { };

class ResearchStudent : public Student { };

 

/* 3. Multiple inheritance */

class Academic { public: void marks() const { cout << "Academic" << endl; } };

class Sports { public: void score() const { cout << "Sports" << endl; } };

class AllRounder : public Academic, public Sports { };

 

/* 4. Hierarchical inheritance: two classes from one base */

class Teacher : public Person { };

 

int main()

{

    B b;

    b.showA();                                  // inherited from A

    b.showB();

 

    ResearchStudent r;

    r.role();                                   // two levels up

 

    AllRounder x;

    x.marks();

    x.score();

 

    Teacher t;

    t.role();

    return 0;

}

 

Output:

A

B

Person

Academic

Sports

Person

 

•      B inherits showA() from A (single). ResearchStudent reaches role() of Person through Student (multilevel).

•      AllRounder has both marks() and score() (multiple); Teacher and Student share Person (hierarchical).

 

4. Base-Class Access Control

4.1 Access specifiers of a class

Specifier

Accessible from

Meaning

public

Members of the class, derived classes, and any outside code

The interface of the class

protected

Members of the class and of its derived classes; not outside code

Implementation shared with derived classes

private

Members of the same class (and friends) only

Hidden implementation

 

A derived class never gains access to the private members of its base class, although they are part of the derived object. The base class can still reach them through its own member functions.

4.2 The base-class access specifier

The access specifier written before the base-class name does not give a derived class more access; it decides how the inherited members are re-labelled in the derived class. A base member can only become equal to or more restricted than its original access.

Member of the base class

public inheritance

protected inheritance

private inheritance

public

public

protected

private

protected

protected

protected

private

private

not accessible

not accessible

not accessible

 

•      Public inheritance keeps the access of public and protected members. It models is-a and is by far the most common.

•      Protected inheritance turns the public members into protected ones; only the derived class and its further derived classes can use the base interface.

•      Private inheritance turns everything accessible into private. The base class is then an implementation detail of the derived class (“implemented in terms of”).

 

4.3 Public inheritance

Program 1.4: What a publicly derived class can and cannot access.

#include <iostream>

using namespace std;

 

class Base {

public:

    int publicValue = 10;

 

protected:

    int protectedValue = 20;

 

private:

    int privateValue = 30;

 

public:

    void displayPrivate() const

    {

        cout << "Private value: " << privateValue << "\n";

    }

};

 

class Derived : public Base {

public:

    void display() const

    {

        cout << "Public value: " << publicValue << "\n";

        cout << "Protected value: " << protectedValue << "\n";

        // cout << privateValue;               // error: private in Base

    }

};

 

int main()

{

    Derived d;

    d.display();

    d.displayPrivate();

    cout << "Public access: " << d.publicValue << "\n";

    // cout << d.protectedValue;               // error: protected

    // cout << d.privateValue;                 // error: private

    return 0;

}

 

Output:

Public value: 10

Protected value: 20

Private value: 30

Public access: 10

 

•      The derived function display() can use publicValue and protectedValue.

•      privateValue is not accessible in Derived; it is reached only through the base-class function displayPrivate().

•      Outside code can use only the public member through a Derived object.

 

If the commented lines are enabled, the compiler gives errors such as:

error: ‘int Base::p’ is private within this context

 

error: ‘int Base::y’ is protected within this context

 

Version Note: Default member initializers such as int publicValue = 10; are a C++11 feature. In C++98 mode GCC accepts them only as an extension and warns:

 

warning: non-static data member initializers only available with ‘-std=c++11’ or ‘-std=gnu++11’ [-Wc++11-extensions]

 

To write code that is valid in C++98, initialise such members in a constructor instead.

4.4 Protected and private inheritance

Program 1.5: The three kinds of derivation applied to the same base class.

#include <iostream>

using namespace std;

 

class Base {

public:

    int a = 10;

 

protected:

    int b = 20;

};

 

class PublicDerived : public Base {

public:

    void display() const

    {

        cout << "PublicDerived: " << a << " " << b << "\n";

    }

};

 

class ProtectedDerived : protected Base {

public:

    void display() const

    {

        cout << "ProtectedDerived: " << a << " " << b << "\n";

    }

};

 

class PrivateDerived : private Base {

public:

    void display() const

    {

        cout << "PrivateDerived: " << a << " " << b << "\n";

    }

};

 

int main()

{

    PublicDerived p;

    ProtectedDerived q;

    PrivateDerived r;

    p.display();

    q.display();

    r.display();

    cout << "Public member through object: " << p.a << "\n";

    // cout << q.a;                            // error: a is protected in q

    // cout << r.a;                            // error: a is private in r

    return 0;

}

 

Output:

PublicDerived: 10 20

ProtectedDerived: 10 20

PrivateDerived: 10 20

Public member through object: 10

 

•      In all three derived classes the member functions can use a (public in Base) and b (protected in Base).

•      The difference appears outside: through a PublicDerived object a is public, but through a ProtectedDerived or PrivateDerived object it is not accessible. Enabling cout << q.a; gives:

 

error: ‘int Base::a’ is inaccessible within this context

 

Inheritance

Outside code can use Base’s public members through the derived object?

Classes derived further can use them?

public

Yes

Yes

protected

No

Yes

private

No

No

 

Note: A using declaration can restore access to selected members in private or protected inheritance (“granting access”, Module 4).

 

5. Conversions between Derived and Base Classes

Because a derived object is-a base object, a pointer or reference to a derived object can be used where a pointer or reference to the base class is expected. This derived-to-base conversion is implicit and is the foundation of polymorphism.

Student s;

Person *p = &s;       // fine: Student is a Person

Person &r = s;        // fine

 

•      The conversion is allowed outside the class only for public inheritance. With protected or private inheritance the base is “inaccessible”, because the is-a relationship is not exposed.

•      The opposite conversion (base to derived) needs an explicit cast and is safe only if the object really is of the derived type (dynamic_cast, Module 7).

 

Using a private derived class where a base pointer is expected gives:

error: ‘Base’ is an inaccessible base of ‘PrivateDerived’

 

Important: Copying a derived object into a base object (not a pointer or reference) copies only the base part; the rest is lost. This is called object slicing and is demonstrated in Module 5.

 

6. Name Hiding in a Derived Class

A function declared in a derived class hides every base-class function of the same name, even if the parameter lists differ. The base functions can still be reached with the scope resolution operator.

Program 1.6: A derived function hides all overloads of the base class.

#include <iostream>

using namespace std;

 

class Base {

public:

    void show() const { cout << "Base::show()" << endl; }

    void show(int x) const { cout << "Base::show(int) " << x << endl; }

};

 

class Derived : public Base {

public:

    // hides ALL Base::show

    void show() const { cout << "Derived::show()" << endl; }

};

 

int main()

{

    Derived d;

    d.show();                 // Derived::show()

    // d.show(5);             // error: the Base overloads are hidden

    d.Base::show(5);          // scope resolution reaches the hidden function

    d.Base::show();

    return 0;

}

 

Output:

Derived::show()

Base::show(int) 5

Base::show()

 

Enabling the call d.show(5) gives:

error: no matching function for call to ‘Derived::show(int)’

 

•      Hiding is not overriding: the function in Derived is a different function that has the same name. Overriding of virtual functions is covered in Module 5.

•      To bring all overloads back into scope, write using Base::show; inside Derived (Modules 2 and 4).

 

7. What Is Not Inherited

Item

Inherited?

Explanation

Data and member functions (not private)

Yes

Accessible according to the access rules above

Private members

Present but inaccessible

Part of the object, but only the base class can use them

Constructors

No

Each class has its own; the base constructor is called by the derived one (Module 3). C++11 allows using Base::Base;

Destructor

No

Every class has its own; base destructors run automatically (Module 3)

Assignment operator

No

The derived class gets its own, which calls the base version

Friend functions and classes

No

Friendship is not inherited (Module 4)

 

8. Quick Revision

•      Syntax: class D : public B { ... };. A derived object contains the base subobject plus its own members.

•      Types: single, multilevel, multiple, hierarchical, hybrid.

•      Private members of the base are never accessible in the derived class. Public inheritance keeps public/protected; protected makes public → protected; private makes everything private.

•      Derived-to-base conversion for pointers and references is implicit and works for public inheritance only.

•      A name declared in the derived class hides all base functions with that name.

 

9. Important Examination Questions

Short-answer questions

1.      Define inheritance. What are the base class and the derived class?

2.      State four advantages of inheritance.

3.      Name the types of inheritance with a diagram.

4.      What is the difference between public, protected and private inheritance?

5.      Can a derived class access the private members of its base class? Explain.

6.      What is name hiding?

7.      Which members of a base class are not inherited?

 

Long-answer and programming questions

1.      Explain inheritance with the syntax and a program using a Person base class and a Student derived class.

2.      Explain the three base-class access specifiers with a table showing the access of public, protected and private members.

3.      Write a program that shows that private members of a base class are not accessible in a derived class.

4.      Write a program that demonstrates all three kinds of inheritance and show which statements in main() are errors.

5.      Explain multilevel and hierarchical inheritance with programs.

 

Hint for question 4. See Programs 1.4 and 1.5 and the error messages in Sections 4.3 and 4.4.

 


No comments:

Post a Comment