1 159.234LECTURE 15 159.234 LECTURE 15 Inheritance Text book p.273-298.

Slides:



Advertisements
Similar presentations
LECTURE LECTURE 17 More on Inheritance, Virtual Inheritance, & Virtual Destructors, 17.
Advertisements

1 Inheritance Concepts n Derive a new class (subclass) from an existing class (base class or superclass). n Inheritance creates a hierarchy of related.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
WEL COME PRAVEEN M JIGAJINNI PGT (Computer Science) MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA, Dc. Sc. & Engg.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Pointer Data Type and Pointer Variables
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Object-Oriented Programming: Polymorphism 1. OBJECTIVES What polymorphism is, how it makes programming more convenient, and how it makes systems more.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
OOP, Virtual Functions and Inheritance
Inheritance. Lecture contents Inheritance Class hierarchy Types of Inheritance Derived and Base classes derived class constructors protected access identifier.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Virtual FunctionstMyn1 Virtual Functions A virtual function is declared in a base class by using the keyword virtual. A function that you declare as virtual.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Overview of C++ Polymorphism
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Problems with assn 3? Discuss at your team meeting tonight.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Inheritance - 3. Virtual Functions Functions defined as virtual are ones that the base expects its derived classes may redefine. Functions defined as.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
A First Book of C++ Chapter 12 Extending Your Classes.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Learning Objectives Relationships Among Objects in an Inheritance Hierarchy. Invoking Base-class Functions from Derived Class Objects. Aiming Derived-Class.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Friends of Template Classes
Polymorphism &Virtual Functions
Inheritance and Run time Polymorphism
Chapter 5 Classes.
Polymorphism & Virtual Functions
Polymorphism Lec
Learning Objectives Inheritance Virtual Function.
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism Polymorphism
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
CISC/CMPE320 - Prof. McLeod
Overview of C++ Polymorphism
CS410 – Software Engineering Lecture #8: Advanced C++ III
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Lecture 6: Polymorphism
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Programming in C# CHAPTER 5 & 6
Computer Science II for Majors
Presentation transcript:

LECTURE LECTURE 15 Inheritance Text book p

2 We frequently classify objects according to some common properties. Mammals have properties such as: warm-blooded higher vertebrates These properties are valid for both an elephant and a mouse, but it is best if we only have to express it only once for all mammals and not have to duplicate for every mammal. Using inheritance, a large body of knowledge can be presented in a more compact way.Inheritance

3 cat The class cat is derived from the class mammal. We say that a cat “is a mammal” and is also a “living creature”. But a cat “is not a reptile”. It is often useful to build our Object-Oriented programs this way. mammal elephant reptile snake cat living creaturesInheritance

4 Sphere Shape TwoDThreeD Circle Rectangle Parent, or base class Child, or derived class How can we code our objects like this? Inheritance

5 #include using namespace std; const static double PI = ; class Shape{ // base class private: char * label; // a string label for the shape }; class TwoD : public Shape{ // two dimensional shapes private: double x, y; }; class ThreeD : public Shape{ // three dimensional shapes private: double x, y, z; }; class Circle : public TwoD{ // Circle extends TwoD public: double area() { return PI * radius * radius; } private: double radius; }; class Rectangle : public TwoD{ public: double area(){ return width * height; } private: double width, height; }; class Sphere : public ThreeD{ public: double volume() { return 4.0 / 3.0 * PI * radius * radius * radius; } private: double radius; }; int main(){ Sphere s1; Circle c1; Shape* shptr; shptr = & s1; shptr = & c1; return 0; } skeleton code!. No output - this is only a skeleton code!. public inheritance Note the public inheritance relations between the classes. base class derived Shape is the base class, and TwoD and ThreeD are derived from it We can group information (and avoid having to duplicate code) in a way that reflects our application and the real things or ideas that our code models. derived Note that in main, a Shape pointer can point to any object that is derived from it.

6 parent For the parent (of class Circle) we might write: class TwoD : public Shape{ public: void print(){cout<< x;} //... protected protected: double x,y; //... }; protected : protected : the data of the class is accessible from within the class itself, to its friend classes, derived classes and their friend classes (derived classes’ friend classes), but not in any other part of the program.Inheritance

7 For the parent class of Circle we write: TwoD class TwoD :public Shape{ public: print() void print(){cout<<…;} //.. protected: x, y double x, y; //.. }; derived class For the derived class we write: Circle:public TwoD class Circle :public TwoD{ public: double area(); private: double radius; }; print() public print() and xy Circle protected x and y, are now also part of Circle (inherited from the parent).Inheritance

8 public inheritance This is called public inheritance. public protected public and protected data of the parent class are inherited in the derived class, and have the same access type. We can have private and protected inheritance as well - we will look at those later. Public inheritance is the most commonly used. :public TwoD class Circle :public TwoD { public: double area(); private: double radius; };Inheritance Next, let’s modify the hierarchy of classes we saw earlier...

9 #include using namespace std; const static double PI = ; class Shape{ // base class private: char * label; // a string label for the shape }; class TwoD : public Shape{ // two dimensional shapes protected: double x, y; }; class ThreeD : public Shape{ // three dimensional shapes protected: double x, y, z; }; class Circle : public TwoD{ // Circle extends TwoD public: double area(){ return PI * radius * radius; } private: double radius; }; class Rectangle : public TwoD{ public: double area(){ return width * height; } private: double width, height; }; class Sphere : public ThreeD{ public: double volume() { return 4.0 / 3.0 * PI * radius * radius * radius; } private: double radius; }; int main(){ Sphere s1; Circle c1; cout << "size of s1 is " << sizeof(s1) << endl; cout << "size of c1 is " << sizeof(c1) << endl; return 0; } Example Output: size of s1 is 36+4 size of c1 is = 4 (char *) + 3 * 8 (double) + 8 (double) + 4 (Class) 32 = 4 (char*) + 2 * 8 (double) + 8 (double)+ 4 (Class) label xy Circles inherit label and x and y labelx, yz Spheres inherit label, x, y and z class incurs an extra overhead

10 Inheritance: Visibility Modifiers Public inheritance: public in base-> public in derived protected-> protected cannot be accessed private-> cannot be accessed Protected inheritance: public in base-> protected in derived protected-> protected cannot be accessed private-> cannot be accessed Private inheritance: public in base-> private in derived protected-> private cannot be accessed private-> cannot be accessed private Default inheritance if not explicitly specified: private

11Inheritance Stud class Stud { public: Stud(char *s, int id); void print(); protected: int stud_id; char surname[64]; }; We can create a new type Grad from Stud with added information : GradpublicStud class Grad : public Stud { public: Grad(char *s, int id, char *t); void print(); protected: char thesis[64]; }; Notice that each class has its own constructor.

12Inheritance Stud Stud:: Stud(char *s, int id) { strcpy(surname,s); stud_id = id; } Gradsid:Stud(s, id) Grad::Grad(char *s, int id, char *t) : Stud(s, id) { strcpy(thesis, t); } initialiser list Grad The constructor for Stud is placed in the initialiser list of the Grad constructor. How do we get initialisation of the information?

13Inheritance It is possible to redefine functions (override) in the derived class to alter its behaviour. print() is defined in both Stud and Grad. print void Stud::print() { cout << surname << " " << stud_id; } print void Grad::print() { Stud::print(); Stud::print(); cout << " " << thesis; } We must use the scope operator, otherwise we get a recursive call. Which function is used is decided at compile time - depending on the type of the object.

14Inheritance derived TwoD If we have many objects derived from the type TwoD and need to calculate their total area: pointers We could store pointers to them in an array. Then work through the array to calculate the total area. Circle c, d Circle c, d; Recte, f Rect e, f; TwoDp TwoD *p[4]; pcpdpepf p[0]=&c; p[1]=&d; p[2]=&e; p[3]=&f; Circle Rect derivedTwoD This is allowed because Circle and Rect are both derived from TwoD.

15Inheritance Now loop through the array: for (int i=0;i<4;i++) { parea() total += p[i]->area(); } Does this work? Yes, if we create virtual functions!

16Polymorphism TwoD class TwoD { public: TwoD(double a, double b) : x(a), y(b) {} virtualareareturn 0; virtual double area(void) {return 0;} protected: double x,y; }; area()virtual area() is a called a virtual function.

17Polymorphism Rect TwoD class Rect : public TwoD{ public: Rect Rect(double a, double b, double ht, double wd) TwoD : TwoD(a,b), h(ht), w(wd) {} virtualreturn w * h; virtual double area(void) {return w * h;} private: double h,w; }; area()virtual area() is a called a virtual function.

18Polymorphism Circle TwoD class Circle : public TwoD{ public: Circle(double a, double b, double rad) : TwoD(a,b), r(rad) {} virtualreturn PI*r*r; virtual double area(void) {return PI*r*r;} private: double r; }; area is a called a virtual function.

19Polymorphism virtual area() is called a virtual function. knows the types of objects that pointers point to The run-time system knows the types of objects that pointers point to! The appropriate function is called when we ask for p[i]->area() for (int i=0;i<4;i++) { p[i]->area() total += p[i]->area(); } Here’s the code segment again: Circle c, d; Rect e, f; TwoD* p[4]; p[0]=&c; p[1]=&d; p[2]=&e; p[3]=&f; dynamic binding This is called dynamic binding. The binding of the call to the actual code to be executed is deferred until run-time.

20Destructors derived new/delete. Be careful with derived objects created on the heap using new/delete. If we delete an object through a base-class pointer delete p[i]; base class virtual Then only the destructor of the base class will be called! Not unless it is declared virtual. base class virtual functions destructorshould also be virtual As a general rule, if a base class contains virtual functions, then the destructor in the base class should also be virtual. See Virtual Destructor - Memory Leak Resolved.cpp

21 Abstract Base Classes Sometimes we want to declare a class, but only allow a programmer to create objects of its derived classes. TwoD circle rect TwoD TwoD TwoD can be made into an abstract class. We can create objects of its derived classes, circle and rect. We can create pointers to the TwoD class. But, we can not create an object of type TwoD. 'pure virtual function The compiler will not allow an object to be created if a class contains a 'pure virtual function '.

22 Pure Virtual Function class TwoD { public: TwoD(double a, double b) : x(a), y(b) {} virtual double area(void) = 0; protected: double x, y; };

23 Multiple Inheritance class Student { public: name char name[32]; char id[10];... }; class Worker { public: name[32 char name[32]; char ird_no[13];... }; Lab_Tutor class Lab_Tutor : public Student, public Worker {... }; Derived classes can have more than one base class:

24Inheritance Lab_Tutor Lab_Tutor A; A.Student:: strcpy(A.Student::name, “Napoleon");... The scope operator is used to resolve name clashes.

25 Virtual Inheritance to remove the ambiguity If we want to remove the ambiguity, we can make the inheritance 'virtual'. class Person { public: char name[32]; }; class Student : virtual public Person { public: char id[10];... }; or public virtual Person

26 Virtual Inheritance class Worker : virtual public Person { public: char ird_no[13];... }; class Lab_Tutor : public Student, public Worker {... }; Now there is only one name associated with Lab_Tutor: Lab_Tutor A; name strcpy(A.name, “Itchy");... class Person { public: char name[32]; }; class Student : virtual public Person { public: char id[10];... };

27 See Demo Codes: virt_err.cpp virt_sel2.cpp abstract.cpp Sample Codes

28 #include using namespace std; class B { public: virtual void foo(int i) {cout<<"\n In Base " << i;} virtual void foo(double d){cout<<"\n In Base "<< d;} }; class D : public B { public: void foo(int k) {cout<<"\n In derived " <<k;} }; int main(){ D d; B b, *pb = &d; b.foo(9); //selects B::foo(int); b.foo(9.5); //selects B::foo(double); d.foo(9); //selects D::foo(int); d.foo(9.5); //selects D::foo(int); // here, the function foo() in class //d is called because we are accessing //the object directly pb -> foo(9); //selects D::foo(int); pb -> foo(9.5); //selects B::foo(double); return 0; } virt_err.cpp Output: In Base 9 In Base 9.5 In derived 9 In Base 9.5

29 #include using namespace std; //virtual function selection class B { public: int i; virtual //comment this out-see what is the result! void print_i() const { cout << i << " inside Base class" << endl; } }; class D : public B { public: //virtual as well void print_i() const { cout << i << " inside Derived class" << endl; } }; int main() { B b; B* pb = &b; //points at a B object D f; D& g=f; f.i = 1 + (b.i = 1); B pb -> print_i(); //call B::print_i() D pb = &f; //points at a D object D pb -> print_i(); //call D::print_i() D g.print_i(); //call D::print_i() } virt_sel2.cpp Output: 1 inside Base class 2 inside Derived class

30 Output (non-virtual): 1 inside Base class 2 inside Base class 2 inside Derived class #include using namespace std; //virtual function selection class B { public: int i; void print_i() const { cout << i << " inside Base class" << endl; } }; class D : public B { public: void print_i() const { cout << i << " inside Derived class" << endl; } }; int main() { B b; B* pb = &b; //points at a B object D f; D& g=f; f.i = 1 + (b.i = 1); B pb -> print_i(); //call B::print_i() D pb = &f; //points at a D object D pb -> print_i(); //call D::print_i() D g.print_i(); //call D::print_i() }

31 Let’s take a peek at how the compiler is actually implementing virtual inheritance.

32 Virtual Inheritance No classes actually contain the virtual base class. Instead, they hold a pointer to a virtual base class table that tells them where in the object the virtual base class exists. ColorListStruct ColorListStruct Base Table Source: Efficient C/C++ Coding Techniques Embedded Systems Conference Boston 2001 Class 304

33 Multiple Virtual Inheritance Each level of virtual inheritance requires its own virtual base table. Source: Efficient C/C++ Coding Techniques Embedded Systems Conference Boston 2001 Class 304

Additional References 34 Technical Report on C++ Performance ISO/IEC TR 18015:2006(E) Next: Inheritance Mastering Visual C++ Efficient C/C++ Coding Techniques Embedded Systems Conference Boston 2001 Class 304

35 Inheritance is the mechanism of deriving new classes from old ones. Through inheritance, a hierarchy of related, code-sharing abstract data types (ADT’s) can be created. The keywords public, private, and protected are used as visibility modifiers for class members. Next:More on inheritance Abstract classesSummary