C++ Modern and Lucid C++ for Professional Programmers

Size: px
Start display at page:

Download "C++ Modern and Lucid C++ for Professional Programmers"

Transcription

1 Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015

2 Inheritance and dynamic Polymorphism base classes, virtual member functions, multiple inheritance Some text-only Slides for self-study will be skipped in lecture

3 Reasons for using Inheritance Mix-in of functionality from empty base class often with own class as template argument e.g., boost::equality_comparable<t> Adapting concrete classes (last week) (no own data members) often better to wrap adaptee as member with inheriting constructors of C++11 convenient e.g., IndexableAdapter<T> 3

4 Inheritance for dynamic binding Implementing a design pattern with dynamic dispatch provide common interface for a variety of dynamically changing or different implementations exchange functionality at run-time treat one or many in an identical way (Composite) Key: base class/interface class provides a common abstraction that is used by clients 4

5 Inheritance Syntax class Base {}; class Derived : public Base{}; In class definition after class name and a colon put the list of base classes, if any sequence is important -> sequence of initialization if multiple base classes with interface inheritance, base class must be public private inheritance is possible, but only useful for mix-in classes that provide friend functions class DerivedPrivateBase : Base {}; struct DerivedPublicBase : Base {}; 5

6 Syntax for multiple inheritance class Base {}; struct MixIn {}; class MultipleBases: public Base, private MixIn {}; sequence is important -> sequence of initialization if multiple base classes exist can mix public and private private inheritance can be used for some mix-in base classes that only add friend functions, like boost/operators.hpp helper classes most often, private base classes are wrong design! more in C++ Advanced module 6

7 Initializing Base Classes class DerivedWithCtor: public Base{ DerivedWithCtor():Base{}{} calling base class ctors put base class ctor call before member initializers in constructor's initializer list (before the body) you can not call "super()" in the body, like in Java -> there is no shorthand for referring base class and it must be fully constructed before the body runs 7

8 Base class ctor before member init class DerivedWithCtor: public Base{ DerivedWithCtor(int i, int j) : Base{i}, mvar{j} {} When initializing own member, base classes are initialized before compiler enforces this rule, even though you can put the list of initializers in wrong order You can also delegate to another constructor of your own class DerivedWithCtor(int i) : DerivedWithCtor{i,i} {} object fully constructed after first ctor is done 8

9 Inheriting and Visibility public: members of the base classes are visible and usable on derived class objects unless the derived class defines members with the same name (even with different parameters) protected: members of the base classes can be used within the derived class private: members of the base classes can not be accessed 9

10 Visibility Rules public: for members forming the interface of the class. usually member functions, type (aliases) to be used, and sometimes constants protected: members to be used by derived classes, if the class is designed as a base class. Often overused or used instead of private which provides better encapsulation. private: members required for the implementation and not to be used accessed by the class' users, often encapsulates member variables 10

11 Dynamic Polymorphism - Important? C++ default mechanisms support value classes copying/moving, deterministic lifetime Operator and function overloading and templates allow polymorphic behavior at compile time this is often more efficient, no run-time indirection Dynamic polymorphism needs object references or (smart) pointers to work syntax overhead base interface must be a good abstraction 11

12 When dynamic polymorphism in C++ Implementing design patterns for run-time flexibility: Strategy, Composite, Decorator client code uses abstract interface and gets parameterized/ called with reference to concrete instance but: if run-time flexibility is not required, templates can implement many patterns with compile-time flexibility as well Often (mis-)used for conceptual hierarchies: is-a relationships even if almost all introductory examples use them 12

13 Why inheritance can be bad Inheritance introduces a very strong coupling between subclasses and their base class you can hardly change the base class You can not get rid of your genes API of base class must fit for all subclasses very hard to get right Conceptual hierarchies are often used as examples but are usually very bad software design, e.g., animal->bird->duck Only one standard library part (the oldest) uses inheritance with dynamic polymorphism: iostreams 13

14 iostreams hierarchy (simplified) Programming against abstractions: abstraction for formatted input abstraction for formatted output concrete class for string input concrete class for string output concrete class for file input concrete class for file output streambuf hierarchy uses virtual member functions! 14

15 Potential problems with inheritance and pass-by-value Assigning or passing by value a derived class value to a base class variable/parameter incurs object slicing only base class member variables are transferred Member functions in derived classes hide base class member with the same name, even if different parameters are used can be problematic, esp. with const/non-const 15

16 Member Hiding Problem #include <iostream> struct Base { void foo(int i) const { std::cout << "foo(i):" << i << '\n'; Overloaded member functions in subclasses hide all parent class }; } member with the same name! struct Derived:Base { void foo() { std::cout << "Derived::foo()\n"; } }; int main(){ hides Base::foo(int) member function alternatively one can specify the overload keyword to be warned Base b{}; b.foo(42); Derived d{}; //d.foo(42); can not call Base::foo(int) on Derived objects d.foo(); } 16

17 Member Using Solving the problem #include <iostream> struct Base { void foo(int i) const { std::cout << "foo(i):" << i << '\n'; by first "using" the base class' members, overloads add to the set of available }; } functions struct Derived:Base { using Base::foo; void foo() { provide all Base::foo members as class members std::cout << "Derived::foo()\n"; } }; int main(){ Base b{}; b.foo(42); Derived d{}; d.foo(42); can now call Base::foo(int) d.foo(); } 17

18 virtual member functions Dynamic polymorphism requires base classes with virtual member functions non-virtual member functions are statically bound and not dynamically class PolymorphicBase { public: client API of abstraction with virtual member virtual void doit() { /* something*/ } }; class Implementor: public PolymorphicBase { public: void doit() { virtual can be omitted in derived class /* something else */ }; } can be marked with override, that will produce a compile error when signature differs from base class member function. IDE will also show that, IMHO override is superfluous. 18

19 Don't forget about const! member functions with and without const are different! you can define both overloads! a derived class providing a member function with different "const-ness" than the base class will not override the baseclass function and the same name will hide the base class 19

20 Calling virtual member functions Value object -> class type used determines function, regardless of virtual Reference or pointer -> virtual member of derived class called through base class reference but not for member functions that aren't virtual 20

21 A bad example #include<iostream> using std::cout; struct Animal { void makesound() { cout << "---\n";} virtual void move() { cout << "---\n";} Animal() { cout << "animal born\n";} ~Animal() { cout << "animal died\n";} }; struct Bird : Animal { virtual void makesound() { cout << "chirp\n";} void move() { cout << "fly\n";} Bird() { cout << "bird hatched\n";} ~Bird() { cout << "bird crashed\n";} }; struct Hummingbird : Bird { void makesound() { cout << "peep\n";} virtual void move() { cout << "hum\n";} Hummingbird() { cout << "hummingbird hatched\n";} ~Hummingbird() { cout << "hummingbird died\n";} }; #include "AnimalBirdHummingbird.h" // bad code for demonstration purpose only! int main(){ cout << "(a) \n"; Hummingbird hummingbird; Bird bird = hummingbird; Animal & animal = hummingbird; cout << "(b) \n"; hummingbird.makesound(); bird.makesound(); animal.makesound(); cout << "(c) \n"; hummingbird.move(); bird.move(); animal.move(); cout << "(d) \n"; } What is the output? What is bad with this code's design? 21

22 Abstract Base Classes: pure virtual struct AbstractBase { virtual ~AbstractBase(){} virtual void doitnow()=0; }; pure virtual member function virtual member functions in a base class can be "pure virtual" or abstract no implementation provided and explicitly said so by = 0; Base classes with virtual members require a virtual destructor if heap allocated without shared_ptr (you shouldn't do that anyway) use shared_ptr<base> consequently for objects on the heap! -> no need to define virtual destructors 22

23 Using polymorphic classes provide base class reference as function parameter, e.g., print(std::ostream &) const-references also work if only const member functions are called (those without side-effects!) no need to heap-allocate subclass objects just pass them as arguments If heap allocated can not be avoided, always use std::shared_ptr<base> and initialize it from a make_shared<concretederived>(...) 23

24 Why the need for virtual keyword? C++'s philosophy is that you do not pay a price for something you do not specify (mostly) Member function calls depending on the dynamic type of an object requires overhead (indirection through function pointer) virtual member functions addresses are put into a table for each class and each object carries a reference to its table, often called the "vtable" result it overhead in object size and run-time for indirect function call virtual member functions can not be inlined by the compiler 24

25 Design Guidelines Low Coupling try to achieve a function's/class' purpose with the minimal set of dependencies inheritance is one of the strongest couplings High Cohesion a function/class should do one thing well do not combine independent functionality split classes/function that do too much Writing unit tests can help to achieve both! 25

26 SOLID principles for Object-Oriented Design 26

27 SRP - Single Responsibility Principle 27

28 OCP - Open Closed Principle 28

29 LSP - Liskov Substitution Principle 29

30 ISP - Interface Segregation Principle 30

31 DIP - Dependency Inversion Principle 31

32 Inheritance and dynamic Polymorphism You should only apply inheritance and virtual member functions if you know what you do do not (like the IDE) create classes with virtual members If you design base classes with polymorphic behavior, understand the common abstraction that they present do not provide too many members or too few extract from existing class(es) the base after you see the commonality arise 32

33 Rules for overriding virtual members Follow Liskov Substitution Principle base class states must be valid for subclass don't break invariants of base class member functions in subclass must accept at least the arguments of the base class and not return values outside the base class member function's range (co- and contravariance) don't change semantics unexpectedly 33

34 Summary Inheritance 3 main uses inherit features, sometimes from empty mix-in class often with CRTP, passing class as template argument of base class adapt features of a base class within a data-less subclass - just use the subclass often member better (but less convenient) dynamic polymorphism with an interface to allow run-time exchange or polymorphic behavior (implement design patterns) 34

35 Merry Christmas 35

Software Engineering

Software Engineering Software Engineering CSC 331/631 - Spring 2018 Object-Oriented Design Principles Paul Pauca April 10 Design Principles DP1. Identify aspects of the application that vary and separate them from what stays

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

C++ Modern and Lucid C++ for Professional Programmers

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers Part 1 Self-study for Introduction to C++ Prof. Peter Sommerlad Director IFS Institute for Software Rapperswil, HS 2017 Thomas Corbat Additional

More information

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli Identify and overcome the difficulties encountered by students when learning how to program List and explain the software development roles played by students List and explain the phases of the tight spiral

More information

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

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

C++ Inheritance and Encapsulation

C++ Inheritance and Encapsulation C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

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

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017 OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus

Modern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus Department I - C Plus Plus Modern and Lucid C++ Advanced for Professional Programmers Part 1 C Plus Plus Recap Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2018 HS2018 Values vs. References

More information

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

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 9 Robert Grimm, New York University 1 Review Last week Modules 2 Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

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

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

ECE 3574: Dynamic Polymorphism using Inheritance

ECE 3574: Dynamic Polymorphism using Inheritance 1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

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

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

G52CPP C++ Programming Lecture 10. Dr Jason Atkin G52CPP C++ Programming Lecture 10 Dr Jason Atkin 1 Last lecture Constructors Default constructor needs no parameters Default parameters Inline functions Like safe macros in some ways Function definitions

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

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

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 3 Move Semantics Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 09.03.2018 HS2018 Move Semantics 2

More information

MODERN AND LUCID C++ ADVANCED

MODERN AND LUCID C++ ADVANCED Informatik MODERN AND LUCID C++ ADVANCED for Professional Programmers Prof. Peter Sommerlad Thomas Corbat Director of IFS Research Assistant Rapperswil, FS 2016 LIBRARY API/ABI DESIGN PIMPL IDIOM HOURGLASS

More information

C++ Modern and Lucid C++ for Professional Programmers

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers part 9 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Functors and Parameterizing STL Functors, Lambdas,

More information

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

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

CS11 Introduction to C++ Fall Lecture 7

CS11 Introduction to C++ Fall Lecture 7 CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Design issues for objectoriented. languages. Objects-only pure language vs mixed. Are subclasses subtypes of the superclass? Encapsulation Encapsulation grouping of subprograms and the data they manipulate Information hiding abstract data types type definition is hidden from the user variables of the type can be declared variables

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 Print Your Name: Page 1 of 8 Signature: Aludra Loginname: CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 (10:00am - 11:12am, Wednesday, October 5) Instructor: Bill Cheng Problems Problem #1 (24

More information

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure you review all previous exams and make sure you fully understand

More information

C++ Programming Lecture 8 Software Engineering Group

C++ Programming Lecture 8 Software Engineering Group C++ Programming Lecture 8 Software Engineering Group Philipp D. Schubert VKrit This time for real (hopefully) Date: 15.12.2017 Time: 15:45 h Your opinion is important! Please use the free text comments

More information

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

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

More information

Polymorphism. Zimmer CSCI 330

Polymorphism. Zimmer CSCI 330 Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)

More information

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

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object Polymorphism C++ Object Oriented Programming Pei-yih Ting NTOU CS 26-1 Contents Assignment to base / derived types of objects Assignment to base / derived types of pointers Heterogeneous container and

More information

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecture 14: Design Workflow Department of Computer Engineering Sharif University of Technology 1 UP iterations and workflow Workflows Requirements Analysis Phases Inception Elaboration

More information

Rushikesh K Joshi. Department of Computer Science and Engineering Indian Institute of Technology Bombay

Rushikesh K Joshi. Department of Computer Science and Engineering Indian Institute of Technology Bombay CS 617 Object Oriented Systems Lecture 6 Classes Implementing Interfaces Open-Closed Principle Self References (This) 3:30-5:00 pm Mon, Jan 21 Rushikesh K Joshi Department of Computer Science and Engineering

More information

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

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

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

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Polymorphism Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Polymorphism Major abstractions of C++ Data abstraction

More information

Rvalue References & Move Semantics

Rvalue References & Move Semantics Rvalue References & Move Semantics PB173 Programming in Modern C++ Nikola Beneš, Vladimír Štill, Jiří Weiser Faculty of Informatics, Masaryk University spring 2016 PB173 Modern C++: Rvalue References &

More information

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

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

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

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

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

Extending Classes (contd.) (Chapter 15) Questions: Extending Classes (contd.) (Chapter 15) Questions: 1 Virtual Functions in C++ Employee /\ / \ ---- Manager 2 Case 1: class Employee { string firstname, lastname; //... Employee( string fnam, string lnam

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecturer: Raman Ramsin Lecture 15: Object-Oriented Principles 1 Open Closed Principle (OCP) Classes should be open for extension but closed for modification. OCP states that we should

More information

CUTE GUTs for GOOD Good Unit Tests drive Good OO Design

CUTE GUTs for GOOD Good Unit Tests drive Good OO Design SET 2010 CUTE GUTs for GOOD Good Unit Tests drive Good OO Design Prof. Peter Sommerlad HSR - Hochschule für Technik Rapperswil Institute for Software Oberseestraße 10, CH-8640 Rapperswil peter.sommerlad@hsr.ch

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages CSE 307: Principles of Programming Languages Classes and Inheritance R. Sekar 1 / 52 Topics 1. OOP Introduction 2. Type & Subtype 3. Inheritance 4. Overloading and Overriding 2 / 52 Section 1 OOP Introduction

More information

CGS 2405 Advanced Programming with C++ Course Justification

CGS 2405 Advanced Programming with C++ Course Justification Course Justification This course is the second C++ computer programming course in the Computer Science Associate in Arts degree program. This course is required for an Associate in Arts Computer Science

More information

Patterns for polymorphic operations

Patterns for polymorphic operations Patterns for polymorphic operations Three small object structural patterns for dealing with polymorphism Alexander A. Horoshilov hor@epsylontech.com Abstract Polymorphism is one of the main elements of

More information

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

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

Overriding Variables: Shadowing

Overriding Variables: Shadowing Overriding Variables: Shadowing We can override methods, can we override instance variables too? Answer: Yes, it is possible, but not recommended Overriding an instance variable is called shadowing, because

More information

CS558 Programming Languages Winter 2013 Lecture 8

CS558 Programming Languages Winter 2013 Lecture 8 OBJECT-ORIENTED PROGRAMMING CS558 Programming Languages Winter 2013 Lecture 8 Object-oriented programs are structured in terms of objects: collections of variables ( fields ) and functions ( methods ).

More information

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

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 3 Part One: - Overview, and 2016 www.cse.unsw.edu.au/ cs6771 2.... What is Object-based Programming? A class uses data abstraction and encapsulation to define

More information

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

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1 CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining

More information

CS24 Week 3 Lecture 1

CS24 Week 3 Lecture 1 CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation

More information

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

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Homework 6. Reading. Problems. Handout 7 CS242: Autumn November

Homework 6. Reading. Problems. Handout 7 CS242: Autumn November Homework 6 Due 14 November, 5PM Handout 7 CS242: Autumn 2012 7 November Reading 1. Chapter 10, section 10.2.3 2. Chapter 11, sections 11.3.2, and 11.7 3. Chapter 12, section 12.4 4. Chapter 13, section

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

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

More C++ : Vectors, Classes, Inheritance, Templates Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

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

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:

More information

Inheritance, Polymorphism and the Object Memory Model

Inheritance, Polymorphism and the Object Memory Model Inheritance, Polymorphism and the Object Memory Model 1 how objects are stored in memory at runtime? compiler - operations such as access to a member of an object are compiled runtime - implementation

More information

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding Conformance Conformance and Class Invariants Same or Better Principle Access Conformance Contract Conformance Signature Conformance Co-, Contra- and No-Variance Overloading and Overriding Inheritance as

More information

explicit class and default definitions revision of SC22/WG21/N1582 =

explicit class and default definitions revision of SC22/WG21/N1582 = Doc No: SC22/WG21/ N1702 04-0142 Project: JTC1.22.32 Date: Wednesday, September 08, 2004 Author: Francis Glassborow & Lois Goldthwaite email: francis@robinton.demon.co.uk explicit class and default definitions

More information

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

And Even More and More C++ Fundamentals of Computer Science And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer June 3, 2013 OOPP / C++ Lecture 9... 1/40 Const Qualifiers Operator Extensions Polymorphism Abstract Classes Linear Data Structure Demo Ordered

More information

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS JAN 28,2011 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 FINALTERM EXAMINATION 14 Feb, 2011 CS304- Object Oriented

More information

Programsystemkonstruktion med C++: Övning 2. Karl Palmskog september 2010

Programsystemkonstruktion med C++: Övning 2. Karl Palmskog september 2010 Programsystemkonstruktion med C++: Övning 2 Karl Palmskog palmskog@kth.se september 2010 Specalfunktioner in classes Constructor constructors of a class initializes class members initial values can be

More information

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

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Today s lecture. CS 314 fall 01 C++ 1, page 1

Today s lecture. CS 314 fall 01 C++ 1, page 1 Today s lecture Midterm Thursday, October 25, 6:10-7:30pm general information, conflicts Object oriented programming Abstract data types (ADT) Object oriented design C++ classes CS 314 fall 01 C++ 1, page

More information

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

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון Overriding עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap A method in a child class overrides a method in the parent class if it has the same name and type signature: Parent void method(int,float)

More information

G52CPP C++ Programming Lecture 12

G52CPP C++ Programming Lecture 12 G52CPP C++ Programming Lecture 12 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture this and static members References Act like pointers Look like values More const And mutable

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211 02 Features of C#, Part 1 Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211 Module Overview Constructing Complex Types Object Interfaces and Inheritance Generics Constructing

More information

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey.

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey. EXPLORATION 36 Virtual Functions Deriving classes is fun, but there s not a lot you can do with them at least, not yet. The next step is to see how C++ implements type polymorphism, and this Exploration

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Summary of the course lectures

Summary of the course lectures Summary of the course lectures 1 Components and Interfaces Components: Compile-time: Packages, Classes, Methods, Run-time: Objects, Invocations, Interfaces: What the client needs to know: Syntactic and

More information

Distributed Real-Time Control Systems. Chapter 13 C++ Class Hierarchies

Distributed Real-Time Control Systems. Chapter 13 C++ Class Hierarchies Distributed Real-Time Control Systems Chapter 13 C++ Class Hierarchies 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according

More information

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

G52CPP C++ Programming Lecture 7. Dr Jason Atkin G52CPP C++ Programming Lecture 7 Dr Jason Atkin 1 This lecture classes (and C++ structs) Member functions inline functions 2 Last lecture: predict the sizes 3 #pragma pack(1) #include struct A

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

Polymorphism. Arizona State University 1

Polymorphism. Arizona State University 1 Polymorphism CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 15 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information