Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Object Oriented Programming with Java
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
1 CSC241: Object Oriented Programming Lecture No 21.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Review of Inheritance. 2 Several Levels of Inheritance Base Class B Derived class D Derived class D1.
Object Oriented Programming
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Derived Classes. C++ 2 Outline  Definition  Virtual functions  Virtual base classes  Abstract classes. Pure virtual functions.
C++ Classes & Data Abstraction
Esempio Polimorfismo1 // Definition of abstract base class Shape #ifndef SHAPE_H #define SHAPE_H class Shape { public: virtual double area() const { return.
1 Inheritance Concepts n Derive a new class (subclass) from an existing class (base class or superclass). n Inheritance creates a hierarchy of related.
Inheritance COMP53 Sept Inheritance Inheritance allows us to define new classes by extending existing classes. A child class inherits all members.
OOP Spring 2007 – Recitation 41 Object Oriented Programming Spring 2007 Recitation 4.
OOP Etgar 2008 – Recitation 71 Object Oriented Programming Etgar 2008 Recitation 7.
UML Class Diagram: class Rectangle
Chapter 10: Inheritance and Polymorphism
DERIVED CLASSES AND INHERITANCE Moshe Fresko Bar-Ilan University Object Oriented Programing
Inheritance and Polymorphism CS351 – Programming Paradigms.
Abstract Classes An abstract class is a base class that will never have an object instantiated from it. –Abstract classes are used only for inheritance,
Chapter 10: Inheritance 1. Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
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.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
 2002 Prentice Hall. All rights reserved. 1 Introduction to Inheritance Inheritance: –1 of 3 main features of OOP –Form of software reusability –(Derived)
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Polymorphism, Abstraction and Virtual Functions. In this slide, we introduce virtual functions and two complex and powerful uses for derived classes that.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Chapter 10 Inheritance and Polymorphism
Polymorphism Polymorphism occurs with objects instantiated from a set of classes related by inheritance to the same ancestor class. –Each class provides.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
© 2007 Lawrenceville Press Slide 1 Chapter 9 Inheritance  One class is an extension of another.  Allows a class to define a specialized type of an existing.
Types of Inheritance in C++. In C++ we have 5 different types of inheritance: – Single Inheritance – Multiple Inheritance – Hierarchical Inheritance –
1 CSC241: Object Oriented Programming Lecture No 17.
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Inheritance in C++ Bryce Boe 2012/08/28 CS32, Summer 2012 B.
MAITRAYEE MUKERJI Object Oriented Programming in C++: Hierarchy / Inheritance.
CSC 143 O 1 CSC 143 Inheritance and Object Oriented Design.
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.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Advanced Program Design with C++
Inheritance and Polymorphism
One class is an extension of another.
Chapter 11: Inheritance and Polymorphism
Types of Programming Languages
CS250 Introduction to Computer Science II
UML Class Diagram: class Rectangle
One class is an extension of another.
Learning Objectives Inheritance Virtual Function.
Polymorphism CT1513.
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Derived Classes in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Inheritance: Polymorphism and Virtual Functions
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Object Oriented Analysis and Design
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.
Presentation transcript:

Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică

2Programming IIObject-Oriented Programming Course #5 Agenda Inheritance in C++ Derived classes Access to parent’s members Constructors and destructor Virtual functions Abstract classes Polymorphism Multiple inheritance Class hierarchies

3Programming IIObject-Oriented Programming Inheritance DEFINITION [Inheritance] Inheritance is a mechanism which allows a class A to inherit members (data and functions) of a class B. We say “A inherits from B”. Objects of class A thus have access to members of class B without the need to redefine them. Inheritance is identified by the phrase: “ kind-of ” at class level (Circle is a kind-of Shape) “ is-a ” at object level (The object circle1 is-a shape.) B is called superclass, supertype, base class or parent class. A is called subclass, subtype, derived class or child class. Introduced in Simula. Example: Person StudentTeacher Inheritance graph Multiple inheritance: a class has 2 or more parent classes. + name : string + courses : List + university : Organization + Age() : double - getPublications() : List+ Grade(topic) : double

4Programming IIObject-Oriented Programming Derived classes (I) Do not multiply objects without necessity. (W. Occam) Inheritance is implemented in C++ through derivation. Derived classes does not have to know implementation details about base classes. Base classes are not “touched” in any way by inheritance. class Employee { public: Employee(String n, Date d); void print() const { cout << „Employee: ” << name << “ Dob: ”<< dob; } private: String name; Date dob; // birth date Date doh; // hiring date }; struct List { void add(Employee* ); }; // WITHOUT INHERITANCE class Manager { Employee emp; // his/her properties as an employee List managedGroup; // list of managed persons }; class Manager : Employee { List managedGroup; // list of managed persons public: Manager(const char* name); int level; }; Manager Employee - name : String - dob : Date - doh: Date + print() - managedGroup : List

5Programming IIObject-Oriented Programming Derived classes (II) Syntax: class DerivedClass : [access modifiers] BaseClass { …. } ; void f(Manager& m, Employee& e) { Employee* pe = &m; // correct Employee& re = m; // correct List l; l.add(&m); l.add(&e); l.add(new Manager(“John Doe”)); l.add(new Employee(“Vasile Popescu”, Date(10,10,1970))); g(m); // ok g(Employee(“Vasile Popescu”, Date(10,10,1970))); // error } As a derived class is a kind-of base class => a derived class object (e.g. Manager) can be used wherever a base class is acceptable (e.g. Employee). But, not the other way around! Example: void g(Employee& e) { Manager* pm = &e; // error: not every // Employee is a manager // brute-force pm = static_cast (&e); cout level; } A class must be defined in order to be used as a base.

6Programming IIObject-Oriented Programming Access control (I) class Manager : public Employee { /* declarations */}; class Manager : protected Employee { /* declarations */}; class Manager : private Employee { /* declarations */}; Member functions of derived class have access to public and protected members of base class, but not to private ones. To control the access to inherited members from base class, access control specifiers are used. Example: If missing, private is considered. Base classAccess controlAccess in derived classExternal access private protected public private private private not accessibleprivate private protected public protected protected protected not accessibleprotected private protected public public public public not accessible protected public not accessible accessible

7Programming IIObject-Oriented Programming Access control (II) class B { int x; protected: int y; public: int z; }; class A : B { void f() { x = 10; // ERROR: private y = 20; // CORRECT! z = 30; // CORRECT! } }; class AA : public B { }; class AAA : AA { void aaa(); }; void f() { B b; A a; AA aa; b.x = 10; // ERROR: private b.y = 20; // ERROR : protected b.z = 30; // CORRECT! a.x = 10; // ERROR: private a.y = 20; // ERROR: private a.z = 30; // ERROR: private aa.x = 10; // ERROR: private aa.y = 20; // ERROR: protected aa.z = 30; // CORRECT! } void AAA::aaa() { x = 10; // ?? y = 20; // ?? z = 30; // ?? } Keep in mind: Data hiding (encapsulation) is a key principle in OOP! => Try to minimize the number of functions that have access to members.

8Programming IIObject-Oriented Programming Constructors and destructor class Manager : public Employee { List managedGroup; public: Manager(const String& s, const Date& d, List &g) : Employee(s, d), managedGroup(g) { } }; An instance of a derived class contains an instance of a base class => need to be initialized using a constructor Use initialization list to call the appropriate constructor Objects are constructed from the bottom to up: base, members, derived class. Example: – allocate memory to hold a Manager instance – call Employee(s,d) to initialize base class – call List(g) to initialize managedList member – execute Manager(…) body Objects are destroyed in the opposite order: derived class, members, base. “Slicing” void f() { List l; Manager m(„Popescu Vasile”, Date(04, 09, 1965), l); Employee c = m; // only Employee part is copied }

9Programming IIObject-Oriented Programming Functions with the same prototype class Manager : public Employee { List managedGroup; public: Manager(String s1, String s2, List &g) : Employee(s1, s2), managedGroup(g) { } void print() const { Employee::print(); // OK: call base class member cout << “Managed group: ” << managedGroup; } }; A member function of derived class may have the same prototype with the function from the base class. Base class function is not impacted, being still accessible using name resolution operator Example: void f() { Manager m(„Popescu”, Date(07, 09, 1978), List()); Employee* pa = &m; m.print(); // Manager::print() m.Employee::print(); // base’s print pa->print(); // Employee::print }

10Programming IIObject-Oriented Programming Virtual functions (I) Two solutions for invoking the appropriate behavior: Type fields Virtual functions DEFINITION [Virtual function, method] A function that can be redefined in each derived class is called virtual function (or method). The prototype of redefined function must have the same name and the same list of arguments, and can only slightly differ in return value. Syntax: virtual ; The compiler will ensure that the right v.f. is invoked for each object. Example: class Employee { public: virtual void print() const { cout << „Employee: ” << name << “ Dob: ”<< dob; } // other declarations }; class Manager { public: void print() const { Employee::print(); // OK: call base class member cout << “Managed group: ” << managedGroup; } }; void f() { Manager m(„Popescu”, Date(07, 09, 1978), List()); Employee* pe = &m; pe->print(); // in fact, Manager::print }

11Programming IIObject-Oriented Programming Virtual functions (II) Q: How the correspondence between object and proper (virtual) function is stored? A: Each instance (object) of a class having v.f. holds a pointer to the VFT ( Virtual Functions Table ) corresponding to its class Example: DEFINITION [Overriding] A function from a derived class with the same name and the same list of arguments as a virtual function in a base class is said to override the base class version of the virtual function. If a virtual function is not overrode in a derived class, then the base class implementation is used. Employee::print Employee::f Employee::print Implementation cout << „Employee: ” << name << “ Dob: ”<< dob; emp void f(Employee* emp) { emp->print(); } vtbl data Employee::vtbl JMP emp->vtbl->print Manager::print Manager::f Manager::print Implementation Employee::print(); cout << managedGroup; vtbl data Manager::vtblemp f(new Employee(…)) f(new Manager(…))

12Programming IIObject-Oriented Programming Polymorphism (I) DEFINITION [Polymorphism] Getting “the right” behavior from base class objects independently of exactly what kind of instance (base of various derived classes) is actually used is called polymorphism. DEFINITION [Polymorphic type] A type with virtual functions is called polymorphic type. To get polymorphic behavior, objects must be manipulated through pointers of references, otherwise no run-time polymorphism is used. Static binding – at compile time. Examples: ― eEmployee e; e.print(); ― Emplyee* pe; pe->Manager::print(); Dynamic binding – at run-time. Examples: ― Employee* pe = new Manager(); pe->print();

13Programming IIObject-Oriented Programming Polymorphism (II) Example: class HeadOfDepartment : public Employee { int departmentID; public: HeadOfDepartment (String& s, Date& d, int id) : Employee(s, d), departmentID(id) { } void print() const { Employee::print(); cout << „Department: ” << departamentID; } }; // polymorphic behavior void printList(List& lista) { for(int i=0; i<lista.size(); i++) lista.get(i)->print(); // right behavior is invoked } int main(int, char*[]) { List l; l.add(new Manager(„Popescu”, Date(01,01,1968), List())); l.add(new HeadOfDepartment(„Alexandrescu”, Date(), 1001)); l.add(new Employee(“Ionescu”, Date(10,10,1970)); printList(l); }

14Programming IIObject-Oriented Programming Abstract classes class Shape { public: virtual void draw() const = 0; // pure virtual }; class Circle { public: void draw() const; } DEFINITION [Pure v.f.] A pure virtual function is a virtual function declared, but not implemented in a base class. A pure virtual function has to be override by all derived classes; otherwise it remains pure. DEFINITION [Abstract class] A class having at least one pure v.f. is called abstract class. Abstract classes cannot be instantiate (it’s an incomplete type). DEFINITION [Interface] An abstract class containing only pure virtual functions and no data members is called interface. Example void Circle::draw() const { cout << “Draw the circle;”; } void f() { Shape sh; // ERROR: Impossible to instantiate abstract classes Shape* sh = new Circle; // ok sh->draw(); // Circle::draw }

15Programming IIObject-Oriented Programming Multiple inheritance (I) class Temporary { Date start, end; // period of collaboration } // Multiple inheritance class Consultant : protected Temporary, public Manager { }; DEFINITION [Multiple inheritance] Multiple inheritance is when a class inherits characteristics from two or more base classes. Increased flexibility of class hierarchies => complex hierarchies (graph-like hierarchies) Example: EmployeeManagerTechnical ExpertTeam Leader Diamond-like inheritance graph

16Programming IIObject-Oriented Programming Multiple inheritance (II). Virtual base class class Base { }; class Derived1 : virtual public Base { }; class Derived2 : virtual public Base { }; class Derived : public Derived1, public Derived 2 { public: Derived() : Base(), Derived1(), Derived2() { } }; Problems: a base class (Employee) may be included twice in a derived class (diamond-like inheritance) – memory wasting – how to access members from a base class that is included twice (Employee)? DEFINITION [Virtual base class] If a class is declared as virtual base, then in a diamond-like inheritance its instance is created and initialized only once. Syntax: class DerivedClass : [private|protected|public] virtual BaseClass { /* decl. */ }; Example: void f() { Derived d; } Need to explicitly call the virtual base class constructor Steps of object initialization: – call virtual base constructor – call constructors of base classes in order of their declaration – initialize derived class members – initialize derived object itself

17Programming IIObject-Oriented Programming Class Hierarchies EmployeeManagerSecretaryDirectorTemporaryTempSecretaryConsultant HOMEWORK: Implement the hierarchy in C++ and override method print for all classes.

18Programming IIObject-Oriented Programming Further Reading [Pop, 2003] Daniel Pop – C++ Programming Language Lecture Notes [Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 12][Stroustrup, 1997] Bjarne Stroustrup – The C++ Programming Language 3rd Edition, Addison Wesley, 1997 [Chapter 12]