Inheritance and aggregation

Similar documents
Advanced I/O Concepts

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

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

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

Polymorphism Part 1 1

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

IS 0020 Program Design and Software Tools

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

Absolute C++ Walter Savitch

C++ Important Questions with Answers

VIRTUAL FUNCTIONS Chapter 10

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

Midterm Exam 5 April 20, 2015

Inclusion Polymorphism

OBJECT ORIENTED PROGRAMMING USING C++

Polymorphism. Zimmer CSCI 330

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

Object Oriented Programming

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

PIC10B/1 Winter 2014 Exam I Study Guide

Inheritance, and Polymorphism.

CS250 Final Review Questions

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class

Major Differences between Java and C++ Programming in C++ Multiple Inheritance

15: Polymorphism & Virtual Functions

C++ Programming: Polymorphism

C++ STREAMS; INHERITANCE AS

Time(int h, int m, int s) { hrs = h; mins = m; secs = s; } void set(int h, int m, int s) { hrs = h; mins = m; secs = s; }

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

04-24/26 Discussion Notes

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

Object Oriented Software Design II

COEN244: Polymorphism

VALLIAMMAI ENGINEERING COLLEGE

Object Oriented Software Design II

Object-Oriented Design (OOD) and C++

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

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

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

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

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

UEE1303(1070) S 12 Object-Oriented Programming in C++

Strict Inheritance. Object-Oriented Programming Winter

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

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

Instantiation of Template class

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

Strict Inheritance. Object-Oriented Programming Spring 2008

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

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

CS304 Object Oriented Programming Final Term

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

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Object-Oriented Programming

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

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

G52CPP C++ Programming Lecture 13

Chapter 5. Object- Oriented Programming Part I

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

Polymorphism. Arizona State University 1

Object Oriented Programming. Solved MCQs - Part 2

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

CPSC 427: Object-Oriented Programming

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

Object-Oriented Programming (OOP) Fundamental Principles of OOP

CS304 Object Oriented Programming

Come and join us at WebLyceum

END TERM EXAMINATION

Object-Oriented Principles and Practice / C++

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Documentation. Programming / Documentation Slide 42

What does it mean by information hiding? What are the advantages of it? {5 Marks}

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015

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:

Data Structures and Other Objects Using C++

Object-Oriented Programming, Iouliia Skliarova

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

Advanced C++ Topics. Alexander Warg, 2017

4 Strings and Streams. Testing.

Tokens, Expressions and Control Structures

Chapter 19 - C++ Inheritance

Example: Count of Points

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

COEN244: Class & function templates

Chapter 5 Object-Oriented Programming

Object-Oriented Concept

1. Write the number of the definition on the right next to the term it defines. (a) copy 4

Reusable and Extendable Code. Composition Example (1) Composition Example (2) CS183-Su'02-Lecture 8 17 June by Eric A. Durant, Ph.D.

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Object-oriented Programming. Object-oriented Programming

Short Notes of CS201

What are the characteristics of Object Oriented programming language?

Module 10 Inheritance, Virtual Functions, and Polymorphism

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

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

Transcription:

Advanced Object Oriented Programming Inheritance and aggregation Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1

Inheritance? Extend a class to create a new class while retaining the members of the original class and adding new members Inheritance is an is-a relationship A derived class is-a base class with more detail added 2

3 Example - Polygons

4 Example: Common attributes

5 Example: Common attributes

6 Example: Base Class - Polygon

7 Derived classes

8 Example: Base and derived classes

9 Example: Base and derived classes

1 Example: Derived classes for Polygons

1 Example: Derived class object

1 Example: Derived class object

1 Notes

1 Inheritance access rules

1 Example: Inheritance types

Polygon Class code (Base Class for Triangle/Square/Rectangle) class Polygons { protected: double area; double perimeter; public: Polygons () {}; ~Polygons () {}; void printarea () const; void printperi () const; }; // Class Polygons /* ====== Polygons :: printarea ====== Prints the area of a polygon. Pre area calculated & stored in area Post area printed */ void Polygons :: printarea () const { cout << "The area of your polygon is " << area << endl; return; } // Polygons printarea /* ====== Polygons :: printperi ====== Prints the perimeter of a polygon. Pre polygon perimeter calculated and stored Post perimeter printed */ void Polygons :: printperi () const { cout << "The perimeter of your polygon is " << perimeter << endl; return; } //Polygons printperi 1

Triangle class code class Triangle : public Polygons { private: double sidea; double sideb; double sidec; void calcarea (); void calcperi (); public: // initialization constructor Triangle (double sideain, double sidebin, double sidecin); }; // Class Triangle Triangle :: Triangle (double sideain, double sidebin, double sidecin) { // Verify sides are valid if ( ((sideain + sidebin) <= sidecin) ((sidebin + sidecin) <= sideain) ((sidecin + sideain) <= sidebin) ) { cout << "Invalid Triangle\n"; exit (100); } // if // Valid Triangle sidea = sideain; sideb = sidebin; sidec = sidecin; calcperi(); calcarea(); return ; } // Triangle initialization constructor void Triangle :: calcarea () { double halfperi = perimeter / 2; area = ( halfperi * (halfperi - sidea) * (halfperi - sideb) * (halfperi - sidec) ); area = sqrt(area); return; } // Triangle calcarea void Triangle :: calcperi () { perimeter = sidea + sideb + sidec; return; } // Triangle calcperi 1

1 Main function code for Triangle Class

Another example: EmpInfo inheritance Base Class class EmpInfo { private: int ID; protected: int Salary; public: char Name[200]; }; Derived Classes class EmpInfo : private SecurityEmp {... } ID (private) inaccessible Salary (protected) private Name (public) private class EmpInfo : protected ImportantEmp {... }; ID (private) inaccessible Salary (protected) protected Name (public) protected 1 class EmpInfo : public RegularEmp {... }; ID (private) inaccessible Salary (protected) protected Name (public) public

2 TIP! Overriding access specifier

Constructor of derived class base-member-initialization list 2

2 Destructor of derived class

2 Example: Employee Class

2 Example: Employee Class

2 Example: Employee Class

Copy constructor of derived class Pass the parameter, which is a reference to the existing derived object, to the constructor of the base class Derived::Derived (const Derived& derivedobject) :Base(derivedObject) { // Derived Part Initialization } The reference type of a base class can also be used to refer to an object of a derived class 2

2 Overriding

2 Overriding Example

Overriding Example int main () { BaseClass baseobj (1); Derived derobj (12, 13); cout << "Using print in base class: \n"; baseobj.print (); 2 cout << "\nusing print in derived class: \n"; derobj.print (); return 0 ; } // main /*Results Using print in base class: **Datum in Base Class is: 1 Using print in derived class: **Datum in Base Class is: 12 **Datum in Derived Class is: 13 */

Polymorphism: overloading Allow many different forms with the same name; The meaning is determined by the context Example in real life open a door open a jar open a book Operator/function overloading is an simple example of polymorphism 3

Polymorphism with inheritance Primary use of polymorphism in object-oriented programming write several versions of a function, each in a separate class related by inheritance When called, the function appropriate for the object being referenced is executed The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run-time (this is called late binding or dynamic binding). (from Wikipedia) 3

3 Pointing Derived Class using Pointer : Static Binding

Pointing Derived Class using Pointer : Static Binding Example 3

Pointing Derived Class using Pointer : Dynamic Binding 3 34

Pointing Derived Class using Pointer : Dynamic Binding Example 3

3 Problem for Destructor & Virtual Destructor

3 Virtual Destructor

Model is required The virtual functions do not force the overriding of a function There are occasions that we want to force the derived class to override (redefine) a function What if in the future we want more polygons? We need to define a model in the base class and let the derived classes follow the model In the base class, we can define the minimum number of functions and the format that is needed for each derived class to include 3

Pure Virtual Function Syntax virtual return_type identifier (parameter list) = 0 Declared in a base class Have no action in base class (just for conceptual requirement) Should be defined in each derived class 3

4 Abstract Class

4 Example: Modified Polygon Class

4 Example: Modified Triangle Class

4 Example: Modified Rectangle Class

4 Example: Modified Square Class

4 Example: Modified main()

4 Example: Modified main() using Base Class pointer

Review: Casting Standard Data Types Can convert a standard data type to another standard data type using either implicit or explicit casting (static casting) Can convert a pointer to a standard data type to a pointer to another standard data type using explicit casting (implicit is not allowed) Let s expand the concept to objects and pointer to objects 4

Class : Upcasting and Downcasting casting of objects (or pointer to objects) is applicable when the classes form a hierarchy of inheritance 4

Upcasting Objects Note: A derived class object is a special type of its base class object 4

Implicit and explicit class conversion int main () { cout << "Before assign: "; Base baseobj (1); baseobj.print (); Derived derobj (3, 5 ); baseobj = derobj; // implicit upcasting cout << "After assign: "; If we use explicit upcasting, baseobj.print (); baseobj = static_cast<base>derobj; return 0; This has the same effect with the implicit casting } // main 5 /* Results Before assign: Value of basedata in class Base is: 1 After assign: Value of basedata in class Base is: 3 */

Downcasting objects Downcasting of objects is not allowed in C++ Notice that a derived class object normally has more data member than the base class The language system does not know how to initialize the extra data 5

5 Upcasting Pointers to Objects

Downcasting Pointers to Objects Downcasting pointers to objects is possible only with dynamic casting Dynamic casting: casting in which the type is determined during the execution of the program, as opposed to during the compilation Recall dynamic binding Dynamic casting can be done only with polymorphic classes that is, classes using virtual functions Syntax dynamic_cast<type> (data) 5

Downcasting Pointers to Objects (Valid case) Dynamic casting is valid only when the base class pointer is already pointing to a derived class object 5

5 5 Downcasting Pointers to Objects (Invalid case) cannot downcast when the base class pointer is not pointing to a derived class object the cast returns a null pointer value (0)

5 Multiple Inheritance

5 Multiple Inheritance : Examples

Another Example: C++ File Library ios_base ios istream ostream iostream istringstream ifstream ofstream ostringstream fstream stringstream 5

Aggregation Inclusion of objects within an object Has-a relationship 5

6 Example: Aggregation

6 Instantiating an aggregated object

Example: Implementation of Aggregation class Student { private: long id; int units; int grpts; Date dob; public: Student (long idin, int unitsin, int grpts, unsigned short day, unsigned short mon, unsigned short year); void print () const; }; // Class Student Student :: Student (long idin, int unitsin, int grptsin, unsigned short dayin, unsigned short monin, unsigned short yearin) : dob (dayin, monin, yearin) { id = idin; units = unitsin; grpts = grptsin; } // Constructor void Student :: print () const { cout << "Student: " << id << " Units: " << units << "\ngr Pts: " << setw (4) << grpts << " Birth Date: "; dob.print(); cout << endl; } // Student 6

Questions? 6 63