INHERITANCE

DICT cshikali2002@yahoo.com

Introduction

Inheritance is the mechanism by which one class can inherit the properties of another. It allows a hierarchy of classes to be build, moving from the most general to the most specific.

Cont..

When one class is inherited by another, the class that is inherited is called the base class. The inheriting class is called the derived class. The process of inheritance begins with the definition of a base class. The base class defines all qualities that will be common to any derived class.

Cont..

In essence, the base class represent the most general description of a set of traits. The derived class inherits those general traits and adds properties that are specific to that class.

classes are like sets. All men are people. John is a man. All dogs are mammals. Mary is a woman.     . but is not the instance of Fruit. All women are people.Inheritance: Classification  An object can be "of" a certain class not its creator.  In this view. Bob is a dog.  An apple is of Fruit. All people are mammals.

.Cont.. man John woman Mary Inheritance ... Classification Animal Mammal People Dog Bird ..

Cont. Classification is a basic idea for understanding the concept of inheritance  ..  Classification arises from the universal need to describe uniformities of collections of instances.

Cont.  Common Design Interface  A base class may define the design requirements for its derived classes by specifying a set of member functions that are required to be provided by each of its derived classes.  Customization  An existing class is used to create a customized version of the class. ..

and therefore dog inherits from mammal A car is-a engine sounds wrong. and therefore inheritance is not natural. then A can be made a subclass of B. A dog is-a mammal. but a car has-a engine. .Inheritance : The is-a Rule  Our idealization of inheritance is captured in a simple rule-of-thumb.    Try forming the English sentences ``An A is-a B''. If it ``sounds right'' to your ear.

Inheritance  This mechanism can be taken as specialization mechanism. .  Instances of the superclass generalize (restrict) the instances of the subclasses.  Instances of a subclass are specializations (additional state and behavior) of the instances of the superclass.  This mechanism also can be taken as generalization mechanism.

.. An approach which allows classes to be created based on an old class.Cont.   The ability of one class to share the behavior of another class without explicit redefinition.  Sharing is also the basic idea of inheritance.

Instances of the subclass must implement. . but that is unimportant for the present argument). (They can also define new  functionality.Inheritance  An Argument for Substitution Instances of the subclass must possess all data areas associated with the parent class. through inheritance at least (if not explicitly overridden) all functionality defined for the parent class.

 It therefore seems reasonable that a variable declared as a parent. . an instance of a child class can mimic the behavior of the parent class.Cont. should be able to hold a value generated from the child class..  Thus.

but are not accessible within the child class.Inheritance  Practical Meaning Data members in the parent are part of the child Behavior defined in the parent are part of the child Note that private aspects of the parent are part of the child.   .

Inheritance is both Extension and Contraction  Because the behavior of a child class is strictly larger than the behavior of the parent. the child is a contraction of the parent. (smaller)  . the child is an extension of the parent. (larger) Because the child can override behavior to make it fit a specialized situation.

Inheritance is the mechanism which allows a class A to inherit properties of a class B. . 2. Inheritance is a mechanism for expressing similarity. 3. Inheritance is the the natural property of classification.What is Inheritance? 1.

Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass.Superclass/Subclass   If class A inherits from class B. A is called subclass of B. . then B is called superclass of A.

Cont. Person superclass subclasses Administrator Faculty member Student ..

c++ class Carpenter extends Person -.Java class Carpenter : Person-.C# .Syntax for Inheritance  Languages use a variety of different syntax to indicate inheritance:    class Carpenter : public Person -.

Declaring Derived Classes in C++ class class_name: access_specifieropt or base_class { Member_list }  access_specifier ::= public|protected|private(default)  .

Cont. any private members of the base class remain private to it and are inaccessible by the derived class. In either case.     The access specifier determines how elements of the base class are inherited by the derived class. When the access specifier for the inherited base class is public all public members of the base class become public members of the derived class.. If the access specifier is private all public members of the base class become private members of the derived class. .

 . it is private by default if the derived class is a class. If the derived class is a struct.Note   If the access specifier is private public members of the base become private members of the derived class. but these are still accessible by member functions of the derived class. public is the default access. If the access specifier is not present.

Example         #include <iostream> using namespace std. } }. class base { int x. } void showx( ) { cout << x << "\n". public: void setx(int n) { x = n. .

.        // Inherit as public class derived : public base { int y. public: void sety(int n) { y = n.Cont. . } void showy( ) { cout << y << "\n". } }.

showy( ). // access member of derived   return 0.sety(20). // access member of derived class class ob.. // access member of base class ob. ob. } .setx(10).showx( ).       int main( ) { derived ob.Cont. // access member of base class ob.

public: void setx(int n) { x = n. class base { int x.Example 2          // This program contains an error #include <iostream> using namespace std. } void showx( ) { cout << x << "\n". . } }.

. } }.Cont.        // Inherit base as private class derived : private base { int y. } void showy( ) { cout << y << "\n". public: void sety(int n) { y = n..

// access member of derived class . // ERROR now private to derived class ob.. // ERROR now private to derived class ob. ob.        int main( ) { derived ob.OK return 0.setx(10).} .showy( ).Cont.showx( ).sety(20).OK ob. // access member of derived class .

Keep in mind that showx( ) and setx( ) are still public within base.Explanation    Both showx( ) and setx() become private to derived and are not accessible outside it. no matter how they are inherited by some derived class. they are accessible from within the derived class. In other words. . This means that an object of type base could access these functions anywhere.

there will be times when you want to keep a member of a base class private but still allow a derived class access to it.Using protected members    A derived class does not have access to the private members of the base class. . However. C++ includes the protected access specifier. To accomplish this.

.   The protected access specifier is equivalent to the private specifier with the sole exception that protected members of a base class are accessible to members of any class derived from that base. Outside the base or derived classes. protected members are not accessible.Cont..

.Cont.  The protected access specifier can occur any where in the class declaration.. although typically it occurs after the (default) private members are declared and before the public members.

       class class-name { // private members protected: //optional // protected members public: //public members }.. .Cont.

it becomes a protected member of the derived class.  When a protected member of a base class is inherited as public by the derived class. If the base class is inherited as private. a protected member of the base becomes a private member of the derived class .

When this is the case. private members of the base remain private to it and are not accessible by the derived class). .Note   A base class can also be inherited as protected by a derived class. public and protected members of the base class become protected members of the derived class (of course.

b = m. . int m) { a = n. } }. class samp { // private by default int a. protected: //still private relative to samp int b.Example 1                // This program illustrate how public. } int geta( ) { return a. public: int c. samp(int n. } int getb( ) { return b. private and // protected members of a class can be accessed #include <iostream> using namespace std.

Cont..
  

int main( ) { samp ob(10, 20); ob.b = 99; // ERROR! b is protected,i.e.

private

 


 

ob.c = 30; // OK, c is public cout << ob.geta( ) << "\n"; cout << ob.getb( ) << ob.c << "\n"; return 0; }

Example 2
       

#include <iostream> using namespace std; class base { protected: // private to base int a, b; // but still accessible by derived public: void setab(int n, int m) { a = n; b = m; } };

Cont..


     


// Inherit as public class derived : public base { int c; public: void setc(int n) { c = n; } // this function has access to a and b from base void showabc( ) { cout << a << " " << b << " " << c << "\n"; } };

Cont..


     

int main( ) { derived ob; // a and b are not accessible here because they are // private to both base and derived. ob.setab(1, 2); ob.setc(3); ob.showabc( ); return 0; }

its public and protected members become protected members of derived and therefore are not accessible within the main( ). the statement:  ob. . 2).e. i.Note  If base is inherited as protected.// would create a compiletime error.setab(1.

height=b.} }. class Polygon { protected: int width. public: void set_values (int a. int b) { width=a.Example 2 // derived classes #include <iostream> using namespace std. . height.

.} }.. class Triangle:public Polygon { public: int area () { return (width * height / 2).Cont. } }. class Rectangle:public Polygon { public: int area () { return (width * height).

return 0.5).area() << endl. trgl.set_values (4.set_values (4. cout << rect. Triangle trgl.. cout << trgl. rect.Cont. int main () { Rectangle rect.5). } .area() << endl.

Next Constructors. and inheritance . destructors.

the constructor functions are executed in order of derivation. the derived class. destructors. or both to have constructor and/or destructor functions.Constructors. . and inheritance   It is possible for the base class. When a base class and a derived class both have constructor and destructor functions.

The reverse is true for destructor functions: the destructor in the derived class is executed before the base class destructor.Cont..  . the base constructor is executed before the constructor in the derived class. That is.   The destructor functions are executed in reverse order.

 .. you then pass the appropriate arguments along to the base class.  To pass an argument to the constructor of the base class. using an expanded form of the derived class' constructor declaration.Cont. a little more effort is needed:  all necessary arguments to both the base class and derived class are passed to the derived class constructor.

The syntax for passing an argument from the derived class to the base class    derived-constructor(arg-list) : base(arg-list) { // body of the derived class constructor } .

Cont. It is permissible for both the derived class and the base class to use the same argument.. It is also possible for the derived class to ignore all arguments and just pass them along to the base.  Here base is the name of the base class. .

} }. } ∼base( ) { cout << "Destructing base\n". . class base { public: base( ) { cout << "Constructing base\n".Example        #include <iostream> using namespace std.

Cont.. } void showj( ) { cout << j << "\n". } }. public: derived(int n) { cout << "Constructing derived\n".           class derived : public base { int j. . j = n. } ∼derived( ) { cout << "Destructing derived\n.

return 0.showj( ). } .// 10 is passed in the normal fashion    o.   int main( ) { derived o(10)..Cont.

Next Multiple inheritance .

In this case.Multiple inheritance  There are two ways that a derived class can inherit from more than one base class:  a derived class can be used as a base class for another derived class. the original base class is said to be an indirect base class of the second derived class. creating a multilevel class hierarchy (hierarchical inheritance). .

Cont.  Second. In this situation. two or more base class are combined to help create the derived class. a derived class can directly inherit more than one base class. This is referred to multiple inheritance.. .

Base class Base class Base class Derived Class Derived Class Derived Class Multilevel Inheritance Multiple Inheritance ..Cont.

Note   If a class B1 is inherited by a class D1. Also the destructor functions are called in reverse order. the constructor functions of all the three classes are called in order of derivation. and D1 is inherited by a class D2. .

.. access base2. ... body of class }.Syntax for Multiple inheritance      class derived-class-name : access base1.. access baseN { // ..

which can be different for each base class.    Here base1 through baseN are the base class names and access the access specifier.Cont. . Destructors are executed in reverse order. left to right that the base classes are specified. constructors are executed in the order.. When multiple base classes are inherited.

. .Cont. each derived class in the chain must pass back to its preceding base any arguments it needs.  When derived class inherits a hierarchy of classes.

.Example: Hierarchical/multilevel          // Multiple inheritance #include <iostream> using namespace std. class B1 { int a. } }. public: B1(int x) { a = x. } int geta( ){ return a.

int y) : B1(y) { // pass y to B1 b = x. } int getb( ) { return b.. } }. .Cont. public: D1(int x.          // Inherit direct base class class D1 : public B1 { int b.

. } // Because bases inherited as public..                // Inherit a derived class and an indirect base class D2 : public D1 { int c. int y. int z) : D1(y. z){ //pass args to D1 c = z. cout << c << "\n". } }.Cont. D2 has access // to public members of both D1 and B1 void show( ) { cout << geta( ) << " " << getb( ) << " ". public: D2(int x.

geta( ) << ob.getb( ) << "\n".Cont. return 0. } . // geta( ) and getb( ) are still public here cout << ob.show( ).. ob. 3). 2.        int main( ) { D2 ob(1.

Therefore. geta( ) becomes a public member of D1. which becomes a public member of D2. . when D1 inherits B1. In this example. they become public members of the derived class.show( ) displays 3 2 1.Explanation     The call to ob. when public members of a base class are inherited as public. B1 is an indirect base class of D2. As you remember. Notice that D2 has access to the public members of both D1 and B1.

Example:Mutiple          #include <iostream> using namespace std. // Create first base class class B1 { int a. } }. public: B1(int x) { a = x. . } int geta( ){ return a.

} }.. } int getb( ) { return b.        // Create second base class class B2 { int b. public: B2(int x) { b = x. .Cont.

. cout << c << "\n". D has access // to public members of both B1 and B2 void show( ) { cout << geta( ) << " " << getb( ) << " ". public B2 { int c. B2(y) { // here z and y are passed directly to B1 and B2 c = x. . int y.Cont. } }. public: D(int x. int z) : B1(z). } // Because bases inherited as public.                // Directly inherit two base classes class D : public B1.

show( ).Cont. } .      int main( ) { D ob(1.. ob. return 0. 2. 3).

Virtual base classes  Consider the following Base Derived 1 Derived 2 Derived 3 .

Derived3 directly inherits both Derived1 and Derived2.     A potential problem exists when multiple base classes are directly inherited by a derived class.Cont. However. Here the base class Base is inherited by both Derived1 and Derived2. . and then again through Derived2. this implies that Base is actually inherited twice by Derived3. This causes ambiguity when a member of Base is used by Derived3. First it is inherited through Derived1..

.Cont. is a reference to a member of Base referring to the Base inherited indirectly through Derived1 or to the Base inherited indirectly through Derived2? .  Since two copies of Base are included in Derived3.

This feature is called a virtual base class. .Solution   C++ includes a mechanism by which only one copy of Base will be included in Derived3.

Cont. .. Doing this prevents two or more copies of the base from being present in any subsequent derived class that inherits the base class indirectly.    In situations like this. in which a derived class indirectly inherits the same base class more than once. The virtual keyword precedes the base class access specifier when it is inherited by a derived class. it is possible to prevent multiple copies of the base from being present in the derived class by having that base class inherited as virtual by any derived classes.

class Base { public: int i. #include <iostream> using namespace std. // Inherit Base as virtual class Derived1 : virtual public Base { public: int j. }.Example             // This program uses a virtual base class. . }.

. class Derived3 : public Derived1. } }. public Derived2 { public: int product( ) { return i*j*k. // However. . only one copy of base is inherited. too class Derived2 : virtual public Base { public: int k.            // Inherit Base as virtual here.Cont. // Here Derived3 inherits both Derived1 and Derived2. }.

i = 10. cout << "Product is: " << ob. // unambiguous because virtual Base   ob. ob.Cont. } .product( ) << "\n". ob. return 0.       int main( ) { Derived3 ob.k = 5.j = 3..

this fragment is perfectly valid:     The only difference between a normal base class and a virtual one occurs when an object inherits the base more than once.NOTE  When a base class is inherited as virtual by a derived class. For example. If virtual base classes are used. multiple copies found. ob.i = 100. only one base class is present in the object. Otherwise. Derived1 ob. assuming the preceding program. . that base class still exists within that derived class.

Forms of Inheritance  Extension. Combination. Variance. The child class inherits features from more than one parent class. but does not change any inherited behavior. (we will consider this latter)    . and the class-subclass relationship is arbitrary. The child class and parent class are variants of each other. The child class restricts the use of some of the behavior inherited from the parent class. The child class adds new functionality to the parent class. Limitation.

 Whole/Partial Inheritance:   If a class inherits all the properties and operations from its superclasses.. that is Whole Inheritance. A class can have more than one superclasses. .Cont.  Single(Simple)/ Multiple inheritance:   A class can inherit from only one superclass. Only some properties are inherited while others are suppressed. This means the inheritance hierarchy forms a tree. else Partial Inheritance.

Benefits of Inheritance        Software Reuse Code Sharing Improved Reliability Consistency of Interface Rapid Prototyping Polymorphism Information Hiding .

Cost of Inheritance     Execution speed Program size Message Passing Overhead Program Complexity .

Next Polymorphism .

Sign up to vote on this title
UsefulNot useful