OOP. Unit:3.3 Inheritance

Similar documents
Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

Friend Functions, Inheritance

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

C++ Important Questions with Answers

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Object-Oriented Programming (OOP) Fundamental Principles of OOP

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Inheritance. Transitivity

CHAPTER 9 INHERITANCE. 9.1 Introduction

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Polymorphism Part 1 1

Sahaj Computer Solutions OOPS WITH C++

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Base class or Super class. Subclass or Derived class

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Interview Questions of C++

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

C++ 8. Constructors and Destructors

Comp151. Inheritance: Initialization & Substitution Principle

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Introduction to Programming Using Java (98-388)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Fundamentals of Programming. Lecture 19 Hamed Rasifard

Computer Programming Inheritance 10 th Lecture

PROGRAMMING IN C++ COURSE CONTENT

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

What are the characteristics of Object Oriented programming language?

Inheritance and Polymorphism

Instantiation of Template class

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

VIRTUAL FUNCTIONS Chapter 10

Chapter 3 Function Overloading

Java Fundamentals (II)

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

ITI Introduction to Computing II

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

C++ (classes) Hwansoo Han

CS105 C++ Lecture 7. More on Classes, Inheritance

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

C++ Basic Syntax. Constructors and destructors. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology

Comp151. Inheritance: Initialization & Substitution Principle

CHAPTER 4 FUNCTIONS. 4.1 Introduction

What is Inheritance?

CS11 Introduction to C++ Fall Lecture 7

Content. Inheritance 6. Object Oriented Programming

ITI Introduction to Computing II

22316 Course Title : Object Oriented Programming using C++ Max. Marks : 70 Time: 3 Hrs.

UNIT - IV INHERITANCE AND FORMATTED I/O

Class, Variable, Constructor, Object, Method Questions

Programming in C# Inheritance and Polymorphism

Binghamton University. CS-140 Fall Dynamic Types

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Comp 249 Programming Methodology

Software Design and Analysis for Engineers

G52CPP C++ Programming Lecture 13

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Short Notes of CS201

Inheritance -- Introduction

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

AC55/AT55 OBJECT ORIENTED PROGRAMMING WITH C++ DEC 2013

Chapter 1: Object-Oriented Programming Using C++

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Java: introduction to object-oriented features

PROGRAMMING LANGUAGE 2

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

CS201 - Introduction to Programming Glossary By

IBS Technical Interview Questions


OOP THROUGH C++(R16) int *x; float *f; char *c;

Increases Program Structure which results in greater reliability. Polymorphism

CS304 Object Oriented Programming Final Term

PESIT Bangalore South Campus

Recharge (int, int, int); //constructor declared void disply();

STRUCTURING OF PROGRAM

Object Oriented Programming

COMP 110/L Lecture 19. Kyle Dewey

Polymorphism. Zimmer CSCI 330

CS 162, Lecture 25: Exam II Review. 30 May 2018

Data Abstraction. Hwansoo Han

COMP 2355 Introduction to Systems Programming

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Inheritance and Polymorphism

Inheritance and Polymorphism

7. C++ Class and Object

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Object Oriented Programming in C++ Basics of OOP

Transcription:

Unit:3.3 Inheritance Inheritance is like a child inheriting the features of its parents. It is a technique of organizing information in a hierarchical (tree) form. Inheritance allows new classes to be built from older and less specialized classes instead of being written from the scratch. So classes are created by first inheriting all the variables and functions defined by some primitive class and then adding specialized variables and functions. Base class and derived class: Inheritance is a technique of building new classes from the existing classes. It is a technique of organizing information in a hierarchical from just like a child inheriting the features of its parents. Inheritance is a prime feature of oops In the process of inheritance, the existing classes that are used to derive new classes are called base classes and the new classes derived from existing classes are called derived classes. When a class is derived from a base class, the derived class inherits all the characteristics of base class and can add new features as refinements and improvements. The great advantage of inheritance is reusability, which ensures ease of distributing class libraries. It improves the program reliability. base class is also called ancestor, parent or super class and derived class is also called as descendent, child or subclass. Feature Base class Feature B Feature C Feature D Defined in derived class Derived class Feature Feature B Feature C 1 Defined in base class lso accessible.

Protected data member: Instead of private and public member there is another type protected member in a class. The purpose of making data member protected in a class is to make such member accessible from the function of the derived class. No other class than derived class function can access the protected data of a base class. Derived class declaration: The derived class inherits all the features of its parent class and adds its own new features. The syntax of declaration of derived class is class derivedclass : < private or public > baseclass // member of derived class // other members. ; Syntax: class class B : public // public derivation private : // data members ; //members of B protected : ; //data members ; public ; class C : private // private derivation //function members ; //members for c ; ; class D : // private derivation default // member of D ; // an example of inheritance #include<iostream.h> #include<conio.h> class one //base class protected: //if private count will be inaccessible to derived class int count; one() count=0; //zero argument constructor void display() cout<<"count="<<count<<endl; void operator ++()//unary operator overloading count++; 2

; class two: public one //derived class void operator --() count--; ; void main() two i; ++i; ++i; i.display(); --i; i.display(); //one j; --j=? and ++j=? //not accessible getch(); output: count=2 count=1 nalysis: 1. protected member (i.e. int count) is introduced in base class. private member can not be accessed by objects of a derived class. The protected members can be accessed by the member functions of derived class. e.g. operator--( ) is defined in derived class two which can access the protected data count of class one. 2. The derived class two inherits all the features of class members base class one. 3. In main( ), object of derived class is created(i.e. two i;) which can use both operator ++( ) defined in base class and operator --( ) in derived class. The derived class two which is child class gets member data count and member function operator ++( ) as inherit attribute of its parent 4. It is not possible to define an object of base class that use -- overloaded operator: since -- is member of derived class. The objects of base class can access the member of its own class. Level of Inheritance The level of inheritance refers to the length of its path from the root ( top base class ). base class itself might have been derived from another classes in the class hierarchy. Inheritance is classified into the following forms based on the levels of inheritance and interrelationship among the classes in their hierarchy. 3

1. Single Inheritance: When a class is derived from only one base class, such derivation is called single inheritance. In single inheritance, base class and derived class exhibits one to one relationship. Following diagram exhibits the point B B is derived from class. class class B :...... ; ; 2. Multiple inheritance : Derivation of a class from two or more base class is called multiple in heritance. In multiple inheritance, the derived class inherits some or all the features of base classes from which it is derived. Following figure shows the multiple inheritance. B Class Class B Class C:, B......... ; ; ; C 3. Hierarchical Inheritance : When several ( more than one ) classes are derived from singled base class z-e. Feature of one class may be inherited by more than class, then it is called hierarchical inheritance. Following figure shows this type of inheritance. B C D Class B : Class C :...... ; Class D :...... 4. Multilevel inheritance : The derivation of a class from another derived class called multilevel inheritance. In figure below, we can see multilevel inheritance 4

e.g nimal B C Mammal # serves as base class for derived class B, which is inturn serves as base class for class C. The class B is known as intermediate base class and the chain BC is inheritance path. Dog 5. Hybrid inheritance : Derivation of class involving more than one form of inheritance is know as hybrid in heritance see fly. B C B C B C D D Hybrid ( multilevel + multiple ) D E [ multilevel, Hierarchical, multiple ] Hybrid 6. Multipath inheritance : Derivation of a class from other derived classes, which are derived from same base class is called multi-path inheritance. Fly. Inheritance and member ccessibility: - Private member of a base class can not be inherited directly to the derived class. The private member of a class is accessible only to the member function of its own. - Making members of base class protected, they are accessible to the member functions of derived class. 5

- protected member can be considered as a hybrid of a private and a public member. Like private members, protected are accessible only to its class member functions and they are invisible outside the class. Like public members, protected members are inherited by derived classes and also accessible to member function of derived class. Following points are to be considered when making members private, public or protected. 1. private member is accessible only to member of the class is which they are declared. They cannot be inherited. 2. private member of the base class can be accessed in the derived class through the member functions of the base class. 3. protected member is accessible to members of its own and any of the members in a derived class. 4. The members that might be used in derived class should be declared as protected rather than private. 5. public member is accessible to members of its own class, member of derived class and even outside the class. 6. Constructors of the base class and derived class are automatically invoked when the derived class is instantiated. If a base class has a constructor with arguments then their invocations must be explicitly specified in the derived class initialization section. Public and private inheritance: The visibility mode in the derivation of new class can be either public or private. Public inheritance: When a class is derived publicly from its base class, the object of derived class can access public member of base class. Private inheritance: When a class is derived privately, the objects of derived class cannot access public member functions of the base class. Since objects can never access private or protected members of a class, the result is that no member of the base class is accessible to objects of the derived class. /*public or private inheritance*/ #include<iostream.h> #include<conio.h> class private : int pvtdata ; protected : int protdata ; int pubdata ; ; 6

class B : public // publicly derived public : void function ( ) int a ; //a = pvtdata ; // error: not accessible. a = protadata ; // ok a = pubdata ; // ok ; class C : private // privately derived. public : void funct ( ) int a ; //a = pvtdata ; // Error : not accessible a = protdata ; // ok a = pubdata ; // ok ; void main() int a ; B objb ; //a = objb.pvtdata ; // error : not accessible //a = objb.protdata ; // error : not accessible a = objb.pubdata ; // ok C objc ; //a = objc.pvtdata; // Error; not accessible //a = objc.protdata; // error; not accessible //a = objc.pubdata; // error; not accessible is private to C getch(); The program specifies a base class,, with private, protected, and public data items. Two classes, B and C, are derived from. B is publicly derived and C is privately derived. Functions in the derived classes can access private or protected members of the base class. Objects of the derived classes cannot access private or protected members of the base class. Objects of the publicly derived class B can access public members of the base class, while objects of the privately derived class C cannot. They can only access the public members of their own derived class. 7

Following figure shows the relationship and accessibility of members in private and public inheritance. Class Private Protected Public Class B: public Private Protected Public obj Class C: private Private Protected Public obj B obj C Member function accessibility: Function type ccess directly to private protected public Class member Yes Yes Yes Derived class member func. No Yes Yes friend function Yes Yes Yes Friend class member Yes Yes Yes Derived Class Constructors: The derived class need not have a constructor as long as the base class has a noargument constructor. If base class has constructor with arguments (one or more) then derived class must have a constructor explicitly defined such that it passes arguments to the base class constructor. 8

In the application of inheritance, objects of derived class are usually created instead of the base class. So derived class should have constructor and pass arguments to the constructor of base class. When an object of a derived class is created, the constructor of the base class is executed first and later the constructor of the derived class is executed. Constructor only in base class: #include <iostream.h > class B B( ) cout <<" No argument constructor of base class executed"; ; class D : public B ; // publicly derived void main ( ) D obj1 ; // accesses base constrictor Run : No argument constructor of base class executed. Similarly, when constructor is present only derived class it is invoked at the object instantiation of derived class Constructor in base and derived class: class B B(int a) cout <<" One argument constructor in base class B"; ; class D : public B D(int a) cout <<" One constructor in derived class D"; ; void main ( ) D objd (3); 9

The compilation generates error like: Cannot find "default constructor to initialize base class 'B' To overcome this error, explicit invocation of a constructor of base class in derived class constructor is needed. class D : public B D( int a ) : B (a) cout <<" One arg.constrictor in derived class D "; ; Run : one arg constructor in base class 'B' one arg constructor in derived class D. Example: //derived class constructor #include<iostream.h> #include<conio.h> class one //base class protected: int count; one() count=0; //zero argument constructor one(int i) count=i; void display() cout<<"count: "<<count<<endl; void operator ++()//unary operator overloading count++; ; class two: public one //derived class two(): one() two(int i): one(i) void operator --() count--; ; void main() two i1; 10

two i2(200); i1.display(); //displays 0 i2.display(); //displays 200 ++i1; ++i1; i1.display(); //displays 2 --i2; i2.display(); //displays 199 getch(); Constructor in multiple inherited classes with explicit invocation #include<iostream.h > class base1 // base class. public : base1() cout << " No arg constructor in abase1 " ; ; class base2 public : base2() cout <<" No a rrg Constructor in base2 "; ; class derived : public base1, public base2 public : derived():base2(), base1() // explicit call cout <<" No arg constructor in derived class " ; ; void main ( ) derived obj ; Run : No arg constructor in base1 No arg constructor in base2 No arg constructor in derived class Here in above program, class derived is derived publicly from class base1 and base2 in order. Constructors of base classes are invoked explicitly in derived class as derived ( ) : base2 ( ), base1 ( ) The order of execution of constructor is same as order as order of inheritance rather than order of explicit call. 11

Constructor invocation for data member initialization: In multiple inheritances, the constructors of base classes are invoked first, in the order in which they appear in the declaration of the derived class. In multilevel inheritance, constructors are invoked in the order of inheritance. For initialization of data members, the derived class object are created and values are supplied either by object of derived class or a constant value can be mentioned in the definition of the constructor. The syntax of defining constructor in derived class derived class (arg list) : Base2 (arg list2),..., Base N (arg list N) // body of derived class constructor mbiguity Resolution in Multiple inheritances: mbiguity is a problem that surfaces in certain situation involving multiple inheritances. Base classes having function with the same name. The class derived from these base classes is not having a function with the name as those of its base classes. Member of a derived class or its objects referring to a member, whose name is the same as those in base classes The problem of ambiguity is resolved using the scope resolution operator as shown in figure. Member access operator Objectname.BaseclassName::MemberName(...) Function to be invoked Base class in which member is defined Instance of derived class Example: of mbiguity //amboguty in member access #include<iostream.h> #include<conio.h> class void show() cout<<" class "; ; class B void show() cout<<" class B "; 12

; class C : public, public B ; void main() C objc; // object of class C //objc.show() ; // ambiguous...error objc.::show() ; // ok invokes show() in class. objc.b::show() ; // ok getch(); The statement objc.show(); is ambiguous as compiler has to choose ::show( ) or B:: show( ). It can be resolved using the scope resolution operator as follows objc.::show( ); refers to the version of show ( ) in the class. nother example: class public : void func ( ) ; ; class B : public. //... ; class C :public //... ; class D : public B, public C //.. ; void main ( ) D obj D; obj D. fun ( ) ; // ambiguous : Overriding Member Functions: Defining a functions in derived class that have same name as those in base class is known as function (Member function) overriding. The member function in derived class overrides the function. B D C 13

Overriding member functions, we can redefine a function in derived class that is previously defined in the base class, giving missing information. Following example shows the overriding of push ( ) and pop ( ) function in typical stack operation. //implementation of stack //overriding member functions #include<iostream.h> #include<stdlib.h> #include<conio.h> #define max 10 class stack protected: int s[max]; int top; stack() //constructor top=-1; ; void push(int x)//put number on stack s[++top]=x; int pop()//take number from stack return s[top--]; class stack2: public stack void push(int x) if(top==max) cout<<"stack Full"; getch(); exit(1); stack::push(x); ; void main() int pop() if(top==-1) cout<<"\nstack empty"; getch(); exit(1); return stack::pop(); 14

stack2 s; s.push(11); s.push(22); s.push(33); cout<<"\nnumber Popped"<<s.pop(); cout<<"\nnumber Popped"<<s.pop(); cout<<"\nnumber Popped"<<s.pop(); cout<<"\nnumber Popped"<<s.pop(); getch(); class stack2 is derived from class stack. Object of stack2 behave in exactly the same way as those of stack, except if attempt is made to push too many items on the stack, or to pop an item from an empty stack. nother example: #include<iostream.h> #include<conio.h> const int SIZE = 25; class teachers private: har empn[size] ; nt numb ; void read() cout << " \nname : " ; cin >> empn ; cout << " \nnumber : " ; cin >> numb ; void write ( ) cout << " \nname:"<< empn ; cout << " \nempno:" << numb ; ; // end teachers. class principal : public teachers private: char desig [SIZE] ; float deduct ; public : void read() teachers :: read ( ) ; cout << " Designation: " ; cin >> desig ; cout << " Deduction : " ; cin >> deduct ; void write() teachers :: write() ; cout << "Designation : " << desig ; cout << " Deduction : " << deduct ; ; 15

class expert : public teachers private : int papers ; public : void read ( ) teachers :: read ( ); cout << " How many papers " ; cin >> papers ; void write ( ) teachers :: write ( ) ; cout << " in No. of papers : " << papers ; ; class extra : public teachers ; void main ( ) principal p1, p2 ; expert e1 ; extra ex1 ; p1. read ( ) ; cout << " \n type in detail of VP : " ; p2. read ( ) ; cout << " \n type in detail of expert: " ; e1. read ( ) ; cout << " \nprinciple : " ; p1.write() ; cout << endl ; cout <<"\nv- principle:" ; p2. write() ; cout << endl; cout << " \nexpert : " ; e1. write() ; cout << endl ; cout << " \nextra : " ; ex1. write() ; getch(); The base class has two member functions read ( ) and write ( ) The first derived class principle declares its own private data desig and deduct and use : : operator to access read ( ) and write of base class. Similarly expert uses its own private data papers of type int and accesses read ( ) and write ( ) of base class The third derived class extra derived from teacher simply contains no members. Since it is derived from teacher it accesses read ( ) and write ( ) member function of base class. bstract Classes The objects created are often the instance of a derived class but not the base class. The base class is just the foundation for building new classes and hence such classes are called abstract base classes or abstract classes. n abstract class is one that has no instances and is not designed to create objects. It is only designed to be inherited. class One 16

; private:. class Two ; void main( ) Two t1; The class One serves as framework for building the derived class and it is treated as a member of the derived class Two. The instance of class One is not created in the function main( ), however it provides a framework for the class Two, so class One can be regarded as bstract class. 17