POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Size: px
Start display at page:

Download "POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE"

Transcription

1 Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public B { // derived class m could be--but need not be--overridden class D2 : public B { // derived class m could be--but need not be--overridden CSC 330 OO Software Design 1 CSC 330 OO Software Design 2 Discussions We have a base class B and two derived classes, D1 and D2. The base class has a pure virtual method m that each derived class can override. Yet the derived classes D1 and D2 are not required to override method m. In object-oriented design, it is sometimes desirable to specify methods that classes such as D1 and D2 should redefine. Shared Interface Definition: A collection of methods that different classes must define, with each class defining the methods in ways appropriate to it. C++ abstract base class can be used to specify methods that any derived class must define if the class is to have objects instantiate it. An abstract base class thus can be used to specify a shared interface. CSC 330 OO Software Design 3 CSC 330 OO Software Design 4 Abstract Base Classes and Pure Virtual Methods An abstract base class is abstract in that no objects can instantiate it. Such a class can be used to specify virtual methods that any derived class must override in, order to have objects instantiate the derived clas. A class must meet one requirement to be an abstract base class: The class must have a pure virtual method. A pure virtual method is one whose declaration ends with the special syntax =0. EXAMPLE virtual void open ( ) = 0; The class ABC has a pure virtual method named open. By making open pure virtual, we thereby make ABC an abstract base class. CSC 330 OO Software Design 5 CSC 330 OO Software Design 6 1

2 EXAMPLE virtual void open( ) = 0; ABC obj; //***** ERROR: ABC is an abstract class Although an abstract base class cannot have objects instantiate it, such a class can have derived classes. A class derived from an abstract base class must override all of the base class's pure virtual methods; otherwise, the derived class itself becomes abstract and no objects can instantiate the derived class. EXAMPLE virtual void open( ) = 0; class X : public ABC { // 1st derived class virtual void open( ) { /* */ // override open( ) class Y : public ABC { // 2nd derived class //*** open is not overridden ABC a1; // **** ERROR: ABC is abstract X x1; // **** Ok, X overrides open( ) and is not abstract Y y1 // **** ERROR: Y is abstract open( ) not defined CSC 330 OO Software Design 7 CSC 330 OO Software Design 8 Discussions Class X overrides the pure virtual method inherited from the abstract base class ABC. Therefore, X is not abstract and may have objects instantiate it. By contrast, Y does not override the pure virtual method inherited from ABC. Therefore, Y becomes an abstract base class and cannot have objects instantiate it. One pure virtual method suffices to make a class an abstract base class. An abstract base class may have other methods that are not pure virtual or not even virtual at all. Further, an abstract base class may have data members. An abstract base class's members may be private, protected, or public. EXAMPLE ABC( ) { /* */ // default constructor ABC( int x ) { /* */ // general constructor ~ABC( ) { /* */ // destructor virtual void open( ) = 0 ; // pure virtual virtual void print( ) const { /* */ // virtual int getcount( ) const { return n; // nonvirtual private: int n; // data member CSC 330 OO Software Design 9 CSC 330 OO Software Design 10 Discussions Restrictions on Pure Functions ABC remains abstract, however, because it still has the pure virtual method open. Therefore, no objects can instantiate ABC. Any class derived from ABC still must override open if the derived class is not to become abstract itself. However, a derived class can simply use the inherited versions of print and getcount. Only a virtual method can be pure. Neither a nonvirtual nor a toplevel function can be declared pure virtual. EXAMPLE void f( ) = 0; void open( ) = 0; //***** ERROR: not a virtual method //***** ERROR: not a virtual method CSC 330 OO Software Design 11 CSC 330 OO Software Design 12 2

3 Uses of Abstract Base Classes class BasicFile { // Abstract Base Class // methods that any derived class should override virtual void open( ) = 0; virtual void close( ) = 0; virtual void flush( ) = 0; class InFile : public BasicFile { virtual void open( ) { /* */ // definition virtual void close( ) { /* */ // definition virtual void flush( ) { /* */ // definition class OutFile : public BasicFile { virtual void open( ) { /* */ // definition virtual void close( ) { /* */ // definition virtual void flush( ) { /* */ // definition Run-Time Identification C++ supports run-time type identification (RTTI), which provides mechanisms to Check type conversions at run time. Determine an object's type at run time. Extend the RTTI provided by C++. FIGURE An abstract base class that specifies an interface shared by two derived classes. CSC 330 OO Software Design 13 CSC 330 OO Software Design 14 The dynamic_cast Operator EXAMPLE In C++ a legal compile-time cast still may result in a run-time error. This danger may be particularly acute when a cast involves pointers or references to objects. The dynamic_cast operator can be used to test, at run time, when a cast involving objects is problematic. class B { //... class D : public B { /* 1 */ D* p; // pointer to derived class /* 2 */ p = new B; //***** ERROR: explicit cast needed /* 3 */ p = static_cast< D* >( new B ) ; // caution! // CSC 330 OO Software Design 15 CSC 330 OO Software Design 16 Discussion In general, it is a bad idea for a derived class pointer to point to a base class object. Nonetheless, this can be done with explicit casting. In line 3, we use a static_cast so that p can point to an object of the base class B. The static_cast in Example is legal but dangerous. In particular, the cast may lead to a run-time error. EXAMPLE class B { void f( ) { // Note: no method m class D : public B { void m( ) { // not in base class D* p; // *** pointer to derived class p = static_cast< D* >( new B ); // caution! p -> m( ) ; // ERROR: there is no B::m! CSC 330 OO Software Design 17 CSC 330 OO Software Design 18 3

4 Discussions Base class B does not have a method named m. In main, the static_cast again allows p to point to a B object. There is no compile-time error from the method invocation p->m(); because p is of type D* and class D has the required method m. Nonetheless, a run-time error results because p points to a B object-that is, to an object that has no method m. We can summarize the problem illustrated in Example by saying that the static_cast does not ensure type safety. The cast is not type safe because the method invocation p->m( ); generates a run-time error, although it is syntactically legal. Dynamic cast cont d p's declared data type of D* implies that p can be used to invoke the method D: : m. The problem is that, at run time, p happens to point to a B object, which has no method m. C++ provides the dynamic_cast operator to check, at run time, whether a cast is type safe. A dynamic_cast has the same basic syntax as a staticcast. However, a dynamic_cast is legal only on a polymorphic type, that is, on a class that has at least one virtual method. CSC 330 OO Software Design 19 CSC 330 OO Software Design 20 EXAMPLE // C has no virtual methods class T { dynamic_cast< T* >( new C ) ; // *** ERROR contains an error because it applies a dynamic_cast to the nonpolymorphic type C. C is nonpolymorphic because it has no virtual methods. Correction virtual void m( ) { // C is now polymorphic The target type of a dynamic_cast, which is specified in angle brackets, must be a pointer or a reference. If T is a class, then T* and T& are legal targets for a dynamic_cast, but T is not. CSC 330 OO Software Design 21 CSC 330 OO Software Design 22 // polymorphic type A has a virtual method EXAMPLE class T { // target class A a1; dynamic_cast< T >( a1 ) // *** ERROR contains an error because the target type is T rather than, for example, T* or T&. EXAMPLE class B { virtual void f( ) { // Note: no method m class D : public B { void m( ) { // not in base class D* p = dynamic_cast< D* > ( new B) ; if ( p ) // is the cast type safe? p->m( ); // if so, invoke p->m( ) else cerr << "Not safe for p to point to a B << endl; CSC 330 OO Software Design 23 CSC 330 OO Software Design 24 4

5 Discussions We initialize p, of type D*, to the value of a dynamic_cast. If T is a type and ptr is a pointer to a polymorphic type, then the expression dynamic_cast< T* > ( ptr ) evaluates to ptr, if the cast is type safe, and to zero (false), if the cast is not type safe. In our example, the cast source is the expression new B, which evaluates to a non-null address if the new operation succeeds. So p would point to the dynamically allocated B object, if the dynamic_cast expression succeeded. If the cast expression failed, as it does in this case, then p is assigned NULL as its value. The dynamic_cast evaluates to NULL (false) precisely because we are trying to have the derived class pointer p point to the base class object created by new B. By checking the result of the dynamic_cast in the if statement, we avoid the run-time error. Summary of dynamic-cast and static-cast C++ provides different casts for different purposes. A static_cast can be applied to any type, polymorphic or not. A dynamic_cast can be applied only to a polymorphic type, and the target type of a dynamic_cast must be a pointer or a reference. In these respects, a static_cast is more basic and general than a dynamic_cast. However, only a dynamic_cast can be used to check at run time whether a conversion is type safe. In this respect, a dynamic_cast is more powerful than a static_cast. CSC 330 OO Software Design 25 CSC 330 OO Software Design 26 COMMON PROGRAMMING ERRORS 1. It is an error to declare a top-level function virtual: virtual bool f( ); //***** ERROR: f is not a method Only methods can be virtual. 2. It is an error to declare a static method virtual: virtual void m( ) ; // ok, object method virtual static void s( ); //***** ERROR: static method 3. If a virtual method is defined outside the class declaration, then the keyword virtual occurs in its declaration but not in its definition: virtual void m1( ) { /*... */ // ok, decl + def virtual void m2( ); // ok, declaration // *** ERROR: virtual should not occur in a definition // outside the class declaration virtual void C::m2( ) { CSC 330 OO Software Design 27 CSC 330 OO Software Design It is an error to declare any constructor virtual, although the destructor may be virtual: virtual C( ); // *** ERROR: constructor virtual C( int ) ; //*** ERROR: constructor virtual ~C( ); // ok, destructor 5. It is bad programming practice not to delete a dynamically created object before the object is inaccessible: void f( ) { C* p = new C; // dynamically create a C object use it //****** ERROR: should delete the object! Once control exits f, the object to which p points can no longer be accessed. Therefore, storage for this object ought to be freed: void f ( ) { C* p = new C; // dynamically create a C object //... use it delete p; // delete it CSC 330 OO Software Design 29 CSC 330 OO Software Design 30 5

6 6. If a method hides an inherited method, then it is an error to try to invoke the inherited method without using its full name: void m( int ) { /* */ // takes 1 arg class Z : public A { public; void m( ) { /* */ // takes 0 args, hides A::m Z z1; z1.m( -999 ) ; // ERROR: Z::m hides A::m z1.a::m( -999 ) // ok, full name z1.m( ); // ok, local method The error remains even if m is virtual because A: :m and Z: :m do not have the same signature. 7. It is an error to expect run-time binding of nonvirtual methods. In the code segment void m( ) { cout << "A::m" << endl; class Z : public A { void m( ) { cout << "Z::m, << endl ; A* p = new Z; // ok, p points to Z object p->m(); // prints A::m, not Z::m as m is not virtual. Because compile-time binding is in effect, the call p->m( ); is to A: m since p's data type is A*. It is irrelevant that p happens to point to a Z object. If we make m a virtual method virtual void m( ) { cout << "A::m " << endl; then the output is Z: :m because run-time binding is in effect and p points to a Z object. CSC 330 OO Software Design 31 CSC 330 OO Software Design It is an error to expect a derived class virtual method D : : m to override a base class virtual method B: :m if the two methods have different signatures. The code segment virtual void m( ); // base class virtual method class Z : public A { //***** Caution: Z::m hides A::m virtual void m( int ) ; // derived class virtual method has two virtual methods named m, but Z: :m does not override A: :m because the two methods have different signatures. For useful polymorphism to occur, the virtual methods must have the same signature, not just the same name. In this example, the two virtual methods are completely unrelated. They simply happen to share a name. 9. It is an error to try to define objects that instantiate an abstract base class: class ABC { // abstract base class virtual void m( ) = 0; // pure virtual method ABC a1; //***** ERROR: ABC is abstract 10. If a class C is derived from an abstract base class ABC and C does not override all of ABC's pure virtual methods, then C is abstract and cannot have objects instantiate it: class ABC { // abstract base class virtual void m1( ) = 0; // pure virtual method virtual void m2( ) = 0; // pure virtual method class C : public ABC { virtual void m1( ) { /* */ // override m1 // m2 not overridden C c1; //***** ERROR: C is abstract CSC 330 OO Software Design 33 CSC 330 OO Software Design A dynamic-cast may be applied only to a polymorphic type, that is, a class with at least one virtual method. Therefore, the following code segment is in error: //... no virtual methods //***** ERROR: C is not polymorphic dynamic_cast< void* >( new C ) ; 12. The target type of a dynamic_cast (that is, the expression in angle brackets) must be a pointer or a reference. Therefore, the following code segment is in error: virtual void m( ) { C c1; //***** ERROR: target type must a pointer or reference A a1 = dynamic_cast< A >( c1 ) ; CSC 330 OO Software Design 35 CSC 330 OO Software Design 36 6

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

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

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

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

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

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

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

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

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued COMP322 - Introduction to C++ Lecture 09 - Inheritance continued Dan Pomerantz School of Computer Science 11 March 2012 Recall from last time Inheritance describes the creation of derived classes from

More information

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

CS105 C++ Lecture 7. More on Classes, Inheritance CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.

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

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

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p

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

A <Basic> C++ Course

A <Basic> C++ Course adapted from Jean-Paul Rigault courses 1 A C++ Course 8 Object-oriented programming 2 Julien Deantoni 2 Outline Dynamic Typing Truncature Cast 3 Variants of class Paragraph Definition of derived

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

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

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

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire

More information

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

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? Or Foo(x), depending on how we want the initialization

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

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete. CMSC433, Fall 2001 Programming Language Technology and Paradigms Adam Porter Sept. 4, 2001 C++ without Classes Don t need to say struct New libraries function overloading confusing link messages default

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

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

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

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00

Introduction to RTTI. Jonathan Hoyle Eastman Kodak 11/30/00 Introduction to RTTI Jonathan Hoyle Eastman Kodak 11/30/00 Overview What is RTTI? typeid( ) function Polymorphism dynamic_cast< > operation RTTI Gotcha s Demo What is RTTI? Run-Time Type Identification

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

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 08 - Inheritance continued School of Computer Science McGill University March 8, 2011 Last Time Single Inheritance Polymorphism: Static Binding vs Dynamic

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

04-24/26 Discussion Notes

04-24/26 Discussion Notes 04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x

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

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

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

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

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

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

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions Dan Pomerantz School of Computer Science 19 March 2012 Overloading operators in classes It is useful sometimes to define

More information

CS OBJECT ORIENTED PROGRAMMING

CS OBJECT ORIENTED PROGRAMMING UNIT-4 INHERITANCE AND RUN TIME POLYMORPHISM Inheritance public, private, and protected derivations multiple inheritance virtual base class abstract class composite objects Runtime polymorphism virtual

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

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

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

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

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

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

Passing arguments to functions by. const member functions const arguments to a function. Function overloading and overriding Templates

Passing arguments to functions by. const member functions const arguments to a function. Function overloading and overriding Templates Lecture-4 Inheritance review. Polymorphism Virtual functions Abstract classes Passing arguments to functions by Value, pointers, refrence const member functions const arguments to a function Function overloading

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED - Polymorphism - Virtual Functions - Abstract Classes - Virtual

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

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

What does it mean by information hiding? What are the advantages of it? {5 Marks} SECTION ONE (COMPULSORY) Question #1 [30 Marks] a) Describe the main characteristics of object-oriented programming. {5 Marks Encapsulation the ability to define a new type and a set of operations on that

More information

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

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4 CS32 - Week 4 Umut Oztok Jul 15, 2016 Inheritance Process of deriving a new class using another class as a base. Base/Parent/Super Class Derived/Child/Sub Class Inheritance class Animal{ Animal(); ~Animal();

More information

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2 UNIT-2 Syllabus for Unit-2 Introduction, Need of operator overloading, overloading the assignment, binary and unary operators, overloading using friends, rules for operator overloading, type conversions

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

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

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

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

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

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

COEN244: Polymorphism

COEN244: Polymorphism COEN244: Polymorphism Aishy Amer Electrical & Computer Engineering Polymorphism means variable behavior / ability to appear in many forms Outline Casting between objects Using pointers to access objects

More information

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Introduction p. xxix The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Language p. 6 C Is a Programmer's Language

More information

Object Oriented Software Design II

Object Oriented Software Design II 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

More information

Chapter 5. Object- Oriented Programming Part I

Chapter 5. Object- Oriented Programming Part I Chapter 5 Object- Oriented Programming Part I 5: Preview basic terminology comparison of the Java and C++ approaches to polymorphic programming techniques introduced before in the context of inheritance:

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

Inheritance. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke.

Inheritance. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke. 1 (32) Inheritance School of Engineering Sciences Program construction in C++ for Scientific Computing 2 (32) Outline 1 2 3 4 3 (32) In the previous lecture we have developed a method for grid generation

More information

Dynamic Binding C++ Douglas C. Schmidt

Dynamic Binding C++ Douglas C. Schmidt Dynamic Binding C++ Douglas C. Schmidt Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.dre.vanderbilt.edu/schmidt/ (615) 343-8197 Motivation When designing a system it is

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova CBook a = CBook("C++", 2014); CBook b = CBook("Physics", 1960); a.display(); b.display(); void CBook::Display() cout

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1 COMP6771 Advanced C++ Programming Week 11 Object Oriented Programming 2016 www.cse.unsw.edu.au/ cs6771 2 Covariants and Contravariants Let us assume that Class B is a subtype of class A. Covariants:

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

Object Oriented Software Design II

Object Oriented Software Design II 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

More information

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory. Pointer C++ Memory Map Once a program is compiled, C++ creates four logically distinct regions of memory: Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack

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

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

Extending Classes (contd.) (Chapter 15) Questions: Extending Classes (contd.) (Chapter 15) Questions: 1 1. The following C++ program compiles without any problems. When run, it even prints out the hello called for in line (B) of main. But subsequently

More information

Inheritance. Chapter 15 & additional topics

Inheritance. Chapter 15 & additional topics Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance

More information

Written by John Bell for CS 342, Spring 2018

Written by John Bell for CS 342, Spring 2018 Advanced OO Concepts Written by John Bell for CS 342, Spring 2018 Based on chapter 3 of The Object-Oriented Thought Process by Matt Weisfeld, with additional material from other sources. Constructors Constructors

More information

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance?

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance? INHERITANCE - Part 1 OOP Major Capabilities Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors encapsulation

More information

INHERITANCE - Part 1. CSC 330 OO Software Design 1

INHERITANCE - Part 1. CSC 330 OO Software Design 1 INHERITANCE - Part 1 Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors CSC 330 OO Software Design 1

More information

Programming 2. Object Oriented Programming. Daniel POP

Programming 2. Object Oriented Programming. Daniel POP Programming 2 Object Oriented Programming Daniel POP Week 5 Agenda 1. Modifiers: friend 2. Objects Wrap-up last week Self-reference Modifiers: static const mutable Object Oriented Programming Friends (I)

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes

More information

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts. asting in C++: Bringing Safety and Smartness to Your Programs of 10 10/5/2009 1:20 PM By G. Bowden Wise The new C++ standard is full of powerful additions to the language: templates, run-time type identification

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Division of Mathematics and Computer Science Maryville College Outline Inheritance 1 Inheritance 2 3 Outline Inheritance 1 Inheritance 2 3 The "is-a" Relationship The "is-a" Relationship Object classification

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

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

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

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; } Multiple choice questions, 2 point each: 1. What output is produced by the following program? #include int f (int a, int &b) a = b + 1; b = 2 * b; return a + b; int main( ) int x=1, y=2, z=3;

More information

Lecture 5: Inheritance

Lecture 5: Inheritance McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability

More information

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

Inheritance and aggregation

Inheritance and aggregation 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

More information

Object-Oriented Concept

Object-Oriented Concept Object-Oriented Concept Encapsulation ADT, Object Inheritance Derived object Polymorphism Each object knows what it is Polymorphism noun, the quality or state of being able to assume different forms -

More information

UNIT - IV INHERITANCE AND FORMATTED I/O

UNIT - IV INHERITANCE AND FORMATTED I/O UNIT - IV INHERITANCE AND FORMATTED I/O CONTENTS: Inheritance Public, private and protected derivations Multiple inheritance Virtual base class Abstract class Composite objects Runtime polymorphism\ Virtual

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Division of Mathematics and Computer Science Maryville College Outline Inheritance 1 Inheritance 2 3 Outline Inheritance 1 Inheritance 2 3 The "is-a" Relationship Object classification is typically hierarchical.

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

Chapter 10 Object-Oriented Programming

Chapter 10 Object-Oriented Programming Chapter 10 Object-Oriented Programming Software Reuse and Independence Objects, Classes, and Methods Inheritance and Dynamic Binding Language Examples: Java, C++, Smalltalk Design Issues and Implementation

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance. Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit III Inheritance The mechanism that allows us to extend the definition of a class without making

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

Inheritance. Chapter 15 & additional topics

Inheritance. Chapter 15 & additional topics Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli Lecture-5 Miscellaneous topics Templates W3101: Programming Languages C++ Miscellaneous topics Miscellaneous topics const member functions, const arguments Function overloading and function overriding

More information