Learning Objectives

advertisement

Learning Objectives

• Base Classes and Derived Classes

• protected Member

• public, protected and private Inheritance

• Inheritance Hierarchy

• Software reusability using Inheritance

• Multiple inheritance

Inheritance

• The mechanism by which one class can inherit the properties of another.

• It allows a hierarchy of classes to be built, moving from the most general to the most specific.

Strongly supports the concept of software reusability (by reusing class)

• This existing class is called the base class and new class is called the derived class.

Base Class:

Defines all qualities common to any derived classes.

Base class tend to be more general

Derived Class:

Inherits those general properties and adds new properties that are specific to that class.

Derived class tend to be more specific

• When creating a class, instead of writing completely new data members and member functions and can specify that the new class should inherit(receive the right) the members of an existing class.

• The derived class inherits some or all of the traits from the base class.

• A class can also inherit properties from more than one class or from more than one level.

Inheritance

– Single Inheritance

• Class inherits from one base class

– Multiple Inheritance

• Class inherits from multiple base classes

– Three types of inheritance:

• public: Derived objects are accessible by the base class objects (focus of this chapter)

• private: Derived objects are inaccessible by the base class

• protected: Derived classes and friends can access protected members of the base class

The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form: class derived-class: access-specifier base-class

Where access-specifier is one of public, protected, or private , and baseclass is the name of a previously defined class. If the access-specifier is not used, then it is private by default.

Example: class base { int x; public: void setx(int n) { x = n; } void showx() { cout << x << ‘\n’ }

}; class derived : public base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘\n’;}

};

Inheritance

• Software reusability using inheritance

• Strongly supports the concept of reusability

• A classes can be reused in several ways

• Once a class has been written and tested ,it can be adapted by other programmers to suit their requirements.

• This is basically done by creating new classes ,

Reusing the properties of the existing ones.

Cont..

• The new class should inherit the members of an existing class.

• This existing class is called the base class and new class is called the derived class.

Example:

• Vehicle as a base class and car as a derived class, then all cars are vehicles

• Vehicles are cars but a vehicle could also be a truck or a boat.

Cont…

• When creating a class, instead of writing completely new data members and member functions and can specify that the new class should inherit(receive the right) the members of an existing class.

• This existing class is called the base class

• Base class tend to be more general

• The new class is called the derived class

• Derived class tend to be more specific.

Cont…

• The mechanism of deriving a new class from an old one is called inheritance or derivation.

• The old class is referred to as the base class and the new one is called the derived class.

• The derived class inherits some or all of the traits from the base class.

• A class can also inherit properties from more than one class or from more than one level.

Cont…

• When a base class is privately inherited by a derived class,

‘public members’ of the base class become ‘private members’ of the derived class and therefore the public members of the base class can only be accessed by the member functions of the derived class.

• They are inaccessible to the objects of the derived class.

• When the base class is publicly inherited,’ public members’ of the base class become ‘public members’ of the derived class and therefore they are accessible to the objects of the derived class. In both the cases, the private members are not inherited and therefore, the private members of a base class will never become the members of its derived class.

Private, public and protected member

Public Inheritance: When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

Protected Inheritance: When deriving from a protected base class, public and protected members of the base class become protected members of the derived class.

Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived class.

Cont..

• When deriving a class from a base class, the

Base class may be inherited (in born) through public, protected or private inheritance.

• When deriving a class with public inheritance, public, public members of the base class become public members of the derived class, and protected members of the base class become protected members of the derived class.

• A base class ‘s private members are never accessible directly from a derived class , but can be accessed through calls to the public and protected members of the base class

Cont…

• When deriving a class with protected inheritance, public and protected members of the base class become protected members of the derived class.

• When deriving a class with private inheritance, public and protected members of the base class become private members of the derived class.

Protected Members

• protected access offers an Intermediate level of protection between public and private access

• A base class’s protected members can be accessed within the body of that base class, by members & friends of that base class, & by members & friends of any classes derived from that base class.

– Derived-class members can refer to public and protected members of the base class simply by using the member names

– Note that protected data “breaks” encapsulation

– When derived-class member function redefines a base-class member function, the base-class member can still be accessed from the derived class by preceding the base-class member name with the base-class name & the scope resolution operator class class-name {

// private members protected:

// protected members public:

// public members

};

public , private and protected

• A derived class can access all the non-private members of its base class.

Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.

Type 1: inherit as public (Implementation of public inheritance)

Base private members protected members public members class base { int x; public: void setx(int n) { x = n; } void showx() { cout << x << ‘\n’ ;}

};

Derived inaccessible protected members public members

#include <iostream> using namespace std; class Shape

{ public: void setWidth(int w)

{ width = w; } void setHeight(int h)

{ height = h; }

// Base class

}

{ protected: int width, height;

}; class Rectangle: public Shape // Derived class

}; int main(void)

{ return (width * height); }

{ public: int getArea()

Rectangle rect; rect.setWidth(5); rect.setHeight(7); cout << "Total area: " << rect.getArea() << endl; // Print the area of the object. return 0;

Type 2: inherit as private

• If the access specifier is private :

– public members of base become private members of derived .

– these members are still accessible by member functions of derived .

Base Derived private members inaccessible protected members private members public members private members

Example: class base { int x; public: void setx(int n) { x = n; } void showx() { cout << x << ‘\n’ }

};

} class derived : private base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘\n’;}

}; int main() { derived ob; ob.setx(10); // Error! setx() is private.

ob.sety(20); // OK!

ob.showx(); // Error! showx() is private.

ob.showy(); // OK!

class derived : private base { int y; public:

// setx is accessible from within derived void setxy(int n, int m) { setx(n); y = m; }

// showx is also accessible void showxy() { showx(); cout<<y<< ‘\n’;}

};

#include <iostream> using namespace std; class Shape

{ int widthb, heightb;

// Base class public: void setWidthb(int w) { widthb = w; } void setHeightb(int h) { heightb = h; } int getAreab() { return (widthb * heightb); }

}; class Rectangle: private Shape // Derived class

{ int widthd, heightd; public: void setWidthd(int wd) { //setWidth(wb); widthd=wd; } void setHeightd(int hd) { //setHeight(hb); heightd=hd; } int getAread() { return (widthd * heightd); }

}; int main(void)

{

Shape sh; sh.setWidthb(5); sh.setHeightb(7);

Rectangle rect; rect.setWidthd(2); rect.setHeightd(3);

} cout << "Total area of Base : " << sh.getAreab() << endl; // Print the area of the object. cout

<< "Total area of Derived : " << rect.getAread() << endl;

// Print the area of the object

.

return 0;

Type 3: inherit as protected

• Sometimes you want to do the following:

– keep a member of a base class private

– allow a derived class access to it

• Use protected members!

• If no derived class, protected members is the same as private members.

Base private members protected members public members

Derived inaccessible protected members protected members

Example: class base { int x; public: void setx(int n) { x = n; } void showx() { cout

<< x << ‘\n’ }

};

#include <iostream> using namespace std; class Shape

{

// Base class protected: int widthb, heightb; public: void setWidth(int w) { widthb = w; } void setHeight(int h) { heightb = h; }

{

}; class Rectangle: protected Shape // Derived class int widthd, heightd; public: void setWidthd(int wb, int wd) { setWidth(wb); widthd=wd; } void setHeightd(int hb, int hd) { setHeight(hb); heightd=hd; } int getAreab() { return (widthb * heightb); } int getAread() { return (widthd * heightd); }

}

}; int main(void)

{

Rectangle rect; rect.setWidthd(5,2); rect.setHeightd(7,3); cout << "Total area of Base : " << rect.getAreab() << endl; // Print the area of the object. cout << "Total area of Derived : " << rect.getAread() << endl; // Print the area of the object.

return 0;

Cont..

• Example:

• Class ABC : private XYZ // private derivation

• {

{ members of ABC

};

Class ABC : public XYZ //public derivation

{ members of ABC

};

Class ABC : XYZ //private derivation by default members of ABC

};

Cont…

• A derived class with only one base class is called single inheritance

• One with several base classes is called multiple inheritance

• The traits (characters) of one class may be inherited by more than one class is known as hierarchical inheritance.

• The mechanism of deriving a class from another

‘derived class’ is known as multilevel inheritance.

• Single inheritance

• Father (Base class)

Cont…

A

• Child (Derived class)

B

Cont…

• Multiple Inheritance: one with several base classes is called multiple inheritance.

allows to combine the features

B of several existing classes as a starting point for defining new classes.

It is like a child inheriting the physical of another.

Cont…

• Hierarchical inheritance

• This is an interesting application of inheritance to use it as a support to the hierarchical design of a program

• Many programming problems can be certain features of one level are

Are shared by many others below that level.

D B C

Con…

• Multilevel inheritance

• Base class Grandfather

B

• Intermediate base Father

C

• Derived class Child

Cont…

• Hybrid Inheritance

Student

A

Test sports

B C

D result

Cont…

• Assume that we have to give weightage for sports before finalising the results.

• The weightage for sports is stored in a separate class called sports.

Inheritance Hierarchy

• Inheritance can be used to modify a class when it did not satisfy the requirements of a particular problem.

• Additional members are added through inheritance to extend the capabilities of a class.

• Inheritance is to use it as a support to the hierarchical design of a program.

• Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level.

Cont..

• Example:

• Hierarchical classification of students in a university.

students arts engine ering medical mech elec civil

Software reusability using inheritance

• Software reuse reduces program development time and cost.

• Inheritance is a form of software reuse in which we create a class that absorbs an existing class’s capabilities, customizes or enhances them. The existing class is called the base class and the new class is referred to as the derived class.

program

• # include<iostream.h>

• # include <conio.h>

• Class student

• {

• Protected: char name[20]; char dept[10]; int rno;

Cont…

• Public: void getdata(); void putdata();

};

{

Clas mark: public student protected: int mark[10]; public: void get(); void put();

};

Cont…

• { protected: int tol; float avg; public: void cal(); void res();

};

Void student ::getdata()

Cont…

• {

} cout<<“ STUDENT MARKLIST”; cout<<“****************”; cout<<“Enter the name:”; cin<<“name; cout<<“Enter the register no:’; cin<<rno; cout<<“enter the department:”; cin>>dept;

Cont…

• Void student :: putdata()

• { cout<<“Majmaah University”; cout<<“****************”; cout<<“name of the student:”<<name; cout<<“Register no:”<<Nno; cout<<“Department :”<<Dept;

}

Cont…

• Void mark:: get()

• { int i;

}

{

Cout<<“enter the mark:”;

For (i=1; i<=6;i++) cin>>mark[i];

Cont…

• }

{ void mark:: put() int i=0; cout<<“\n ************* cout<<“endl<<“\n’tsem no subcode subject mark <<endl;

Cout<<“\n **********************”

Cout<<endl<<“\t 4\t 1234\t cs1<<mark[i+1]<<endl;

Cont…

• Cout<<end1<<“\t 4\t 56789 physics

<<mark[i+2]<<endl;

• Cout<<endl<<“\t 4\t 34566’t c++

<<mark[i+3]<<endl;

• Cout<<endl<<“\t 4\t 45677 english”\t

<<mark [i+4]<<endl;

• Cout<<endl<<“\t 4 45678 Lab”\t

<<mark[i+5]<<endl;

• Cout<<endl<<“\t 4 89076 arabic”\t

<<mark[i+6]<<endl;

• }

Cont…

• Void result:: cal ()

• {

Int I; tot=0; for (i=1; i<=6; i++)

{ tot =tot+mark[i];

} avg=tot /6;

}

Cont…

• Void result :: res()

• { cout<<“The total is :”<<tot; cout<<“ The average is :”<<avg;

}

{

Void main()

Clrscr();

Cont…

• Result A[10];

• Int I,n;

• Cout <<“Enter the no of students:”;

• Cin>>n;

• For (i=1;i<=n;i++)

• {

A[i].getdata();

A[i].get();

A[i].cal();

}

• For (i=1;i<=n;i++)

• {

A[i].get data();

A[i].get();

A[i].cal();

} for (i=1;i<=n; i++)

{

A[i].putdata();

Cont…

• A[i].put();

• A[i].res();

• Get ch();

• }

• Getch();

• }

Cont…

Cont…

• Majmaah University

• ****************

• Name of the student: xxxxx

• Register no : …….

• Department : math

• Total is 500

• Average is :84

Cont…

• Output:

• Enter the no of students: 1 student marklist

• **************

• Enter the name:xxxxx

• Enter the register no: …….

• Enter the department : Math

• Enter the marks:

Virtual functions

• when a derived class inherits from a base class, an object of the derived class may be referred to via a pointer or reference of either the base class type or the derived class type.

• Abstract classes and pure virtual functions:

• A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class, if that class is not abstract . Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly. A subclass of an abstract class can only be instantiated directly if all inherited pure virtual methods have been implemented by that class or a parent class.

Pure virtual methods typically have a declaration

(signature) and no definition (implementation).

Cont…

• As an example, an abstract base class

MathSymbol may provide a pure virtual function doOperation(), and derived classes Plus and

Minus implement doOperation() to provide concrete implementations. Implementing doOperation() would not make sense in the

MathSymbol class, as MathSymbol is an abstract concept whose behaviour is defined solely for each given kind (subclass) of MathSymbol.

Similarly, a given subclass of MathSymbol would not be complete without an implementation of doOperation().

Cont…

• Although pure virtual methods typically have no implementation in the class that declares them, pure virtual methods in C++ are permitted to contain an implementation in their declaring class, providing fallback or default behaviour that a derived class can delegate to, if appropriate.

• Pure virtual functions can also be used where the method declarations are being used to define an interface - similar to what the interface keyword in Java explicitly specifies. In such a use, derived classes will supply all implementations. In such a design pattern , the abstract class which serves as an interface will contain

only pure virtual functions, but no data members or ordinary methods. In C++, using such purely abstract classes as interfaces works because C++ supports multiple inheritance . However, because many OOP languages do not support multiple inheritance, they often provide a separate interface mechanism. An example is the Java programming language .

Cont…

• Object-oriented languages typically manage memory allocation and deallocation automatically when objects are created and destroyed.

However, some object-oriented languages allow a custom destructor method to be implemented, if desired. If the language in question uses automatic memory management, the custom destructor (generally called a finalizer in this context) that is called is certain to be the appropriate one for the object in question. For example, if an object of type Wolf that inherits Animal is created, and both have custom destructors, the one called will be the one declared in Wolf.

• In manual memory management contexts, the situation can be more complex, particularly as relates to static dispatch. If an object of type Wolf is created but pointed to by an Animal pointer, and it is this Animal pointer type that is deleted, the destructor called may actually be the one defined for Animal and not the one for Wolf, unless the destructor is virtual. This is particularly the case with C++, where the behavior is a common source of programming errors.

Cont…

• Child inherits what its ancestors have. Base classes can't inherit what the child has(such as a new function or variable). Virtual functions are simply functions that can be overrided by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called.

• Let's suppose we have 4 classes: class A, class B, class C and class D. The classes are inherited by this way : A->B->C-D, where A is the base class.

Download