Object Oriented Software Design II

Similar documents
Object Oriented Software Design II

Design Patterns in C++

Object Oriented Software Design II

Programming Languages: OO Paradigm, Polymorhism and Class Members

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

Polymorphism Part 1 1

Polymorphism. Zimmer CSCI 330

15: Polymorphism & Virtual Functions

Object Oriented Software Design

COMP322 - Introduction to C++

C++ Programming: Polymorphism

Inheritance, and Polymorphism.

C++ (classes) Hwansoo Han

G52CPP C++ Programming Lecture 13

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

Introduction to the C programming language

Introduction to the C programming language

Object-Oriented Programming, Iouliia Skliarova

04-24/26 Discussion Notes

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

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

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

CSE 303: Concepts and Tools for Software Development

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

And Even More and More C++ Fundamentals of Computer Science

VIRTUAL FUNCTIONS Chapter 10

Extending Classes (contd.) (Chapter 15) Questions:

Programming in C++: Assignment Week 6

G Programming Languages - Fall 2012

Programming, numerics and optimization

Design Patterns in C++

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

L4: Inheritance. Inheritance. Chapter 8 and 10 of Budd.

C++ (Non for C Programmer) (BT307) 40 Hours

Design Patterns in C++

INHERITANCE: EXTENDING CLASSES

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Fast Introduction to Object Oriented Programming and C++

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Data Structures and Other Objects Using C++

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

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

More C++ : Vectors, Classes, Inheritance, Templates

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:

Introduction to Inheritance

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

C++ classes. Giuseppe Lipari April 27, Scuola Superiore Sant Anna Pisa

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

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Lecture 5: Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Extending Classes (contd.) (Chapter 15) Questions:

Fundamentals of Programming

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Advanced course on C++

CS304 Object Oriented Programming Final Term

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

Object-Oriented Concept

ECE 3574: Dynamic Polymorphism using Inheritance

Design Patterns in C++

Design Patterns in C++

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Class CSE F. *slides are from CSE S at SKKU & at MIT

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Object Oriented Software Design

Programming Languages: OO Paradigm, Objects

Object Oriented Programming. Solved MCQs - Part 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

EL2310 Scientific Programming

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

What is an algorithm?

Object Oriented Software Design

VALLIAMMAI ENGINEERING COLLEGE

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Chapter 5. Object- Oriented Programming Part I

Templates. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. June 8, 2009

Object Oriented Programming

Inheritance. A mechanism for specialization A mechanism for reuse. Fundamental to supporting polymorphism

OBJECT ORIENTED PROGRAMMING

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

Object Oriented Software Design II

Inheritance. Chapter 15 & additional topics

Object Oriented Software Design II

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Inheritance. Chapter 15 & additional topics

Dynamic Binding C++ Douglas C. Schmidt

Transcription:

Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 1 / 32 Outline 1 Inheritance 2 Virtual functions 3 Virtual Destructors 4 Pure virtual functions G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 2 / 32

Code reuse In C++ (like in all OO programming), one of the goals is to re-use existing code There are two ways of accomplishing this goal: composition and inheritance Composition consists defining the object to reuse inside the new object Composition can also expressed by relating different objects with pointers each other Inheritance consists in enhancing an existing class with new more specific code G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 4 / 32 Inheritance int i; protected: int j; A() : i(0),j(0) { ~A() { int get() const {return i; int f() const {return j; class B : public A { int i; B() : A(), i(0) { ~B() { void set(int a) {j = a; i+= j int g() const {return i; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 5 / 32

Syntax How to define the derived class class B : public A { int i; B() : A(), i(0) { ~B() { void set(int a) { j = a; i+= j; int g() const { return i; class B derives publicly from A Therefore, to construct B, we must first construct A j is a member of A declared as protected; therefore, B can access it i instead is a member of B. There if another i that is a private member of A, so it cannot be accessed from B G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 6 / 32 Use of Inheritance Now we can use B as a special version of A int main() { B b; cout << b.get() << endl; // calls A::get(); b.set(10); cout << b.g() << endl; b.g(); A *a = &b; // Automatic type conversion (upcasting) a->f(); B *p = new A; // error! See./examples/04.inheritance-examples/example1.cpp G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 7 / 32

Public inheritance Public inheritance means that the derived class inherits the same interface of the base class All members in the public part of A are also part of the public part of B All members in the protected part of A are part of the protected part of B All members in the private part of A are not accessible from B. This means that if we have an object of type B, we can use all functions defined in the public part of B and all functions defined in the public part of A. G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 8 / 32 Overloading and hiding There is no overloading across classes... int f(int, double); class B : public A {... void f(double); int main() { B b; b.f(2,3.0); // ERROR! A::f() has been hidden by B::f() to get A::f() into scope, the using directive is necessary using A::f(int, double); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 9 / 32

Upcasting It is possible to use an object of the derived class through a pointer to the base class. void f() {... class B : public A { void g() {... A* p; p = new B(); p->f(); p->g(); A pointer to the base class The pointer now points to an object of a derived class Call a function of the interface of the base class: correct Error! g() is not in the interface of the base class, so it cannot be called through a pointer to the base class! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 10 / 32 References Same thing is possible with references void f() {... class B : public A { void g() {... void h(a &) { h.f(); h.g(); B obj; Function h takes a reference to the base class Of course, it is possible to call functions in the interface of the base class This is an error! g() is not in the interface of A Calling the function by passing a reference to an object of a derived class: correct. h(obj); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 11 / 32

Extension through inheritance Why this is useful? All functions that take a reference (or a pointer) to A as a parameter, continue to be valid and work correctly when we pass a reference (or a pointer) to B This means that we can reuse all code that has been written for A, also for B In addition, we can write additional code specifically for B Therefore, we can reuse existing code also with the new class We can extend existing class to implement new functionality What about modifying (customize, extend, etc.) the behaviour of existing code without changing it? G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 12 / 32 Virtual functions Let s introduce virtual functions with an example G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 14 / 32

Implementation class Shape { protected: double x,y; Shape(double x1, double y2); virtual void draw() = 0; class Circle : public Shape { double r; Circle(double x1, double y1, double r); virtual void draw(); class Rect : public Shape { double a, b; Rect(double x1, double y1, double a1, double b1); virtual void draw(); class Triangle : public Shape { double a, b; Triangle(double x1, double y1, double a1, double b1); virtual void draw(); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 15 / 32 We would like to collect shapes Let s make an array of shapes Shapes * shapes[3]; shapes[0] = new Circle(2,3,10); shapes[1] = new Rect(10,10,5,4); shapes[2] = new Triangle(0,0,3,2); // now we want to draw all the shapes... for (int i=0; i<3; ++i) shapes[i]->draw(); We would like that the right draw function is called However, the problem is that Shapes::draw() is called The solution is to make draw virtual G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 16 / 32

Virtual functions class Shape { protected: double x,y; Shape(double xx, double yy); void move(double x, double y); virtual void draw(); virtual void resize(double scale); virtual void rotate(double degree); move() is a regular function draw(), resize() and rotate() are virtual see shapes/ class Circle : public Shape { double r; Circle(double x, double y, double r); void draw(); void resize(double scale); void rotate(double degree); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 17 / 32 Virtual table When you put the virtual keyword before a function declaration, the compiler builds a vtable for each class Circle vptr void draw() void resize() void rotate() Rect vptr void draw() void resize() void rotate() Triangle vptr void draw() void resize() void rotate() G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 18 / 32

Calling a virtual function When the compiler sees a call to a virtual function, it performs a late binding, or dynamic binding each object of a class derived from Shape has a vptr as first element. It is like a hidden member variable The virtual function call is translated into get the vptr (first element of object) move to the right position into the vtable (depending on which virtual function we are calling) call the function G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 19 / 32 Dynamic binding vs static binding Which function are called in the following code? void f() { cout << "A::f()" << endl; g(); virtual void g() { cout << "A::g()" << endl; class B : public A { void f() { cout << "B::f()" << endl; g(); virtual void g() { cout << "B::g()" << endl;... A *p = new B; p->g(); p->f(); B b; A &r = b; r.g(); r.f(); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 20 / 32

Overloading and overriding When you override a virtual function, you cannot change the return value Simply because the compiler will not know which function to actually call There is only one exception to the previous rule: if the base class virtual method returns a pointer or a reference to an object of the base class...... the derived class can change the return value to a pointer or reference of the derived class G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 21 / 32 Overload and override Examples Correct virtual A& f(); int g(); class B: public A { virtual B& f(); double g(); Wrong virtual A& f(); class C: public A { virtual int f(); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 22 / 32

Overloading and overriding When you override a virtual function, you cannot change the return value Simply because the compiler will not know which function to actually call There is only one exception to the previous rule: if the base class virtual method returns a pointer or a reference to an object of the base class...... the derived class can change the return value to a pointer or reference of the derived class G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 23 / 32 Overload and override Examples Correct virtual A& f(); int g(); class B: public A { virtual B& f(); double g(); Wrong virtual A& f(); class C: public A { virtual int f(); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 24 / 32

Destructors What happens if we try to destruct an object through a pointer to the base class? A(); ~A(); class B : public A { B(); ~B(); int main() { A *p; p = new B; //... delete p; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 26 / 32 Virtual destructor This is a big mistake! The destructor of the base class is called, which destroys only part of the object You will soon end up with a segmentation fault (or illegal access), or memory corruption To solve the problem, we have to declare a virtual destructor If the destructors are virtual, they are called in the correct order G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 27 / 32

Restrictions Never call a virtual function inside a destructor! Can you explain why? You can not call a virtual function inside a constructor in fact, in the constructor, the object is only half-built, so you could end up making a wrong thing during construction, the object is not yet ready! The constructor should only build the object Same thing for the destructor during destruction, the object is half destroyed, so you will probably call the wrong function G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 28 / 32 Restrictions Example class Base { string name; Base(const string &n) : name(n) { virtual string getname() { return name; virtual ~Base() { cout << getname() << endl; class Derived : public Base { string name2; Derived(const string &n) : Base(n), name(n + "2") { virtual string getname() {return name2; virtual ~Derived() { G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 29 / 32

Pure virtual functions A virtual function is pure if no implementation is provided Example: class Abs { virtual int fun() = 0; virtual ~Abs(); class Derived public Abs { Derived(); virtual int fun(); virtual ~Derived(); This is a pure virtual function. No object of Abs can be instantiated. One of the derived classes must finalize the function to be able to instantiate the object. G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 31 / 32 Interface classes If a class only provides pure virtual functions, it is an interface class an interface class is useful when we want to specify that a certain class conforms to an interface Unlike Java, there is no special keyword to indicate an interface class more examples in section multiple inheritance G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 29, 2012 32 / 32