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

Size: px
Start display at page:

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

Transcription

1 POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1

2 Abstract Base Classes class B { // base class virtual void m( ) { /*... */ } // define m 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 2

3 Discussions We have a base class B and two derived classes, D1 and D2. The base class has a 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 define. CSC 330 OO Software Design 3

4 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 4

5 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. CSC 330 OO Software Design 5

6 EXAMPLE class ABC { // Abstract Base Class 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 6

7 EXAMPLE class ABC { // Abstract Base Class 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. CSC 330 OO Software Design 7

8 EXAMPLE class ABC { // Abstract Base Class 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 8

9 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. CSC 330 OO Software Design 9

10 EXAMPLE class ABC { // Abstract Base Class 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 10

11 Discussions 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. CSC 330 OO Software Design 11

12 Restrictions on Pure Functions Only a virtual method can be pure. Neither a nonvirtual nor a toplevel function can be declared pure virtual. EXAMPLE void f( ) = 0; class C { void open( ) = 0; //***** ERROR: not a virtual method //***** ERROR: not a virtual method CSC 330 OO Software Design 12

13 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 FIGURE An abstract base class that specifies an interface shared by two derived classes. CSC 330 OO Software Design 13

14 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++. CSC 330 OO Software Design 14

15 The dynamic_cast Operator 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. CSC 330 OO Software Design 15

16 EXAMPLE class B { //... class D : public B { // int main( ) { /* 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 16

17 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. CSC 330 OO Software Design 17

18 EXAMPLE class B { void f( ) { } // Note: no method m class D : public B { void m( ) { } // not in base class int main( ) { 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 18

19 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. CSC 330 OO Software Design 19

20 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 20

21 EXAMPLE class C { // C has no virtual methods class T { // int main( ) { 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. CSC 330 OO Software Design 21

22 Correction class C { 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 22

23 EXAMPLE class A { // polymorphic type // A has a virtual method class T { // target class // int main( ) { A a1; dynamic_cast< T >( a1 ) // *** ERROR // } contains an error because the target type is T rather than, for example, T* or T&. CSC 330 OO Software Design 23

24 EXAMPLE class B { virtual void f( ) { } // Note: no method m class D : public B { void m( ) { } // not in base class int main( ) { 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 24

25 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. CSC 330 OO Software Design 25

26 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 26

27 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: class C { virtual void m( ) ; // ok, object method virtual static void s( ); //***** ERROR: static method CSC 330 OO Software Design 27

28 COMMON PROGRAMMING ERRORS cont d 3. If a virtual method is defined outside the class declaration, then the keyword virtual occurs in its declaration but not in its definition: class C { 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 28

29 COMMON PROGRAMMING ERRORS cont d 4. It is an error to declare any constructor virtual, although the destructor may be virtual: class C { virtual C( ); // *** ERROR: constructor virtual C( int ) ; //*** ERROR: constructor virtual ~C( ); // ok, destructor CSC 330 OO Software Design 29

30 COMMON PROGRAMMING ERRORS cont d 5. It is bad programming practice not to delete a dynamically created object before the object is inaccessible: class C { // 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 30

31 COMMON PROGRAMMING ERRORS cont d 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: class A { void m( int ) { /* */ } // takes 1 arg class Z : public A { public; void m( ) { /* */ } // takes 0 args, hides A::m int main( ) { 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. CSC 330 OO Software Design 31

32 COMMON PROGRAMMING ERRORS cont d 7. It is an error to expect run-time binding of nonvirtual methods. In the code segment class A { void m( ) { cout << "A::m" << endl; } class Z : public A { void m( ) { cout << "Z::m, << endl ; } int main( ) { 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 class A { 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 32

33 COMMON PROGRAMMING ERRORS cont d 8. 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 class A { virtual void m( ); class Z : public A { // base class virtual method //***** 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. CSC 330 OO Software Design 33

34 COMMON PROGRAMMING ERRORS cont d 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 34

35 COMMON PROGRAMMING ERRORS cont d 11. 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: class C { //... no virtual methods int main( ) { //***** ERROR: C is not polymorphic dynamic_cast< void* >( new C ) ; // } CSC 330 OO Software Design 35

36 COMMON PROGRAMMING ERRORS cont d 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: class C { virtual void m( ) { } class A { // int main( ) { C c1; //***** ERROR: target type must a pointer or reference A a1 = dynamic_cast< A >( c1 ) ; // } CSC 330 OO Software Design 36

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations

More information

Description of Class Mutation Mutation Operators for Java

Description of Class Mutation Mutation Operators for Java Description of Class Mutation Mutation Operators for Java Yu-Seung Ma Electronics and Telecommunications Research Institute, Korea ysma@etri.re.kr Jeff Offutt Software Engineering George Mason University

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

CIS 190: C/C++ Programming. Polymorphism

CIS 190: C/C++ Programming. Polymorphism CIS 190: C/C++ Programming Polymorphism Outline Review of Inheritance Polymorphism Car Example Virtual Functions Virtual Function Types Virtual Table Pointers Virtual Constructors/Destructors Review of

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Constructor, Destructor, Accessibility and Virtual Functions

Constructor, Destructor, Accessibility and Virtual Functions Constructor, Destructor, Accessibility and Virtual Functions 182.132 VL Objektorientierte Programmierung Raimund Kirner Mitwirkung an Folienerstellung: Astrit Ademaj Agenda Constructor Destructors this

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship. CSCI 253 Object Oriented Design: Java Review OOP George Blankenship George Blankenship 1 Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation Abstract Data Type (ADT) Implementation

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

Compile-time type versus run-time type. Consider the parameter to this function:

Compile-time type versus run-time type. Consider the parameter to this function: CS107L Handout 07 Autumn 2007 November 16, 2007 Advanced Inheritance and Virtual Methods Employee.h class Employee public: Employee(const string& name, double attitude, double wage); virtual ~Employee();

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1 The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose

More information

Classes and Pointers: Some Peculiarities (cont d.)

Classes and Pointers: Some Peculiarities (cont d.) Classes and Pointers: Some Peculiarities (cont d.) Assignment operator Built-in assignment operators for classes with pointer member variables may lead to shallow copying of data FIGURE 3-22 Objects objectone

More information

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though. Stewart Weiss Inheritance is a feature that is present in many object-oriented languages such as C++, Eiffel, Java, Ruby, and Smalltalk, but each language implements it in its own way. This chapter explains

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI 621213

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI 621213 MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI 621213 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Sub code: CS2203 SEM: III Sub Name: Object Oriented Programming Year: II UNIT-IV PART-A 1. Write the

More information

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin SE 360 Advances in Software Development Object Oriented Development in Java Polymorphism Dr. Senem Kumova Metin Modified lecture notes of Dr. Hüseyin Akcan Inheritance Object oriented programming languages

More information

Advanced Data Structures

Advanced Data Structures C++ Advanced Data Structures Chapter 8: Advanced C++ Topics Zhijiang Dong Dept. of Computer Science Middle Tennessee State University Chapter 8: Advanced C++ Topics C++ 1 C++ Syntax of 2 Chapter 8: Advanced

More information

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang 6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang Today s topics Why objects? Object-oriented programming (OOP) in C++ classes fields & methods objects representation

More information

Basic Logic Gates. Logic Gates. andgate: accepts two binary inputs x and y, emits x & y. orgate: accepts two binary inputs x and y, emits x y

Basic Logic Gates. Logic Gates. andgate: accepts two binary inputs x and y, emits x & y. orgate: accepts two binary inputs x and y, emits x y Basic andgate: accepts two binary inputs x and y, emits x & y x y Output orgate: accepts two binary inputs x and y, emits x y x y Output notgate: accepts one binary input x, emits!y x Output Computer Science

More information

OpenCL Static C++ Kernel Language Extension

OpenCL Static C++ Kernel Language Extension OpenCL Static C++ Kernel Language Extension Document Revision: 04 Advanced Micro Devices Authors: Ofer Rosenberg, Benedict R. Gaster, Bixia Zheng, Irina Lipov December 15, 2011 Contents 1 Overview... 3

More information

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008. 1

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008. 1 A Review of the OOP Polymorphism Concept Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008. 1 Outline Overview Type Casting and Function Ambiguity Virtual Functions,

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

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

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g

More information

C++ Support for Abstract Data Types

C++ Support for Abstract Data Types Topics C++ Support for Abstract Data Types Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.cs.wustl.edu/schmidt/ (615) 343-8197 Describing Objects Using ADTs Built-in vs.

More information

Introduction Object-Oriented Network Programming CORBA addresses two challenges of developing distributed systems: 1. Making distributed application development no more dicult than developing centralized

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

PHP Object Oriented Classes and objects

PHP Object Oriented Classes and objects Web Development II Department of Software and Computing Systems PHP Object Oriented Classes and objects Sergio Luján Mora Jaume Aragonés Ferrero Department of Software and Computing Systems DLSI - Universidad

More information

CS193j, Stanford Handout #10 OOP 3

CS193j, Stanford Handout #10 OOP 3 CS193j, Stanford Handout #10 Summer, 2003 Manu Kumar OOP 3 Abstract Superclass Factor Common Code Up Several related classes with overlapping code Factor common code up into a common superclass Examples

More information

explicit class and default definitions revision of SC22/WG21/N1582 = 04-0022 and SC22/WG21/ N1702 04-0142

explicit class and default definitions revision of SC22/WG21/N1582 = 04-0022 and SC22/WG21/ N1702 04-0142 Doc No: SC22/WG21/ N1717 04-0157 Project: Programming Language C++ Date: Friday, November 5, 2004 Author: Francis Glassborow & Lois Goldthwaite email: francis@robinton.demon.co.uk explicit class and default

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

1. Polymorphism in C++...2

1. Polymorphism in C++...2 1. Polymorphism in C++...2 1.1 Polymorphism and virtual functions... 2 1.2 Function call binding... 3 1.3 Virtual functions... 4 1.4 How C++ implements late binding... 6 1.4.1 Why do I have to know at

More information

Software Engineering 1 EEL5881 Spring 2009. Homework - 2

Software Engineering 1 EEL5881 Spring 2009. Homework - 2 Software Engineering 1 EEL5881 Spring 2009 Homework - 2 Submitted by Meenakshi Lakshmikanthan 04/01/2009 PROBLEM STATEMENT: Implement the classes as shown in the following diagram. You can use any programming

More information

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List

MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List MSP430 C/C++ CODE GENERATION TOOLS Compiler Version 3.2.X Parser Error/Warning/Remark List This is a list of the error/warning messages generated by the Texas Instruments C/C++ parser (which we license

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance Introduction to C++ January 19, 2011 Massachusetts Institute of Technology 6.096 Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance We ve already seen how to define composite datatypes

More information

N3458: Simple Database Integration in C++11

N3458: Simple Database Integration in C++11 N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,

More information

Java Programming Language

Java Programming Language Lecture 1 Part II Java Programming Language Additional Features and Constructs Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Subclasses and

More information

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= Much of the surrounding prose written by Andy Maag, CS193D instructor from years ago. The compiler will supply a default (zero-argument)

More information

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class CHAPTER 5 CLASSES class head class struct identifier base spec union class name 5.1 Object-Oriented and Procedural Programming 5.2 Classes and Objects 5.3 Sample Application: A Clock Class 5.4 Sample Application:

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Part I. Multiple Choice Questions (2 points each):

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

CEC225 COURSE COMPACT

CEC225 COURSE COMPACT CEC225 COURSE COMPACT Course GEC 225 Applied Computer Programming II(2 Units) Compulsory Course Duration Two hours per week for 15 weeks (30 hours) Lecturer Data Name of the lecturer: Dr. Oyelami Olufemi

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from

More information

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) { Operators C and C++ 6. Operators Inheritance Virtual Alastair R. Beresford University of Cambridge Lent Term 2008 C++ allows the programmer to overload the built-in operators For example, a new test for

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Grundlagen der Betriebssystemprogrammierung

Grundlagen der Betriebssystemprogrammierung Grundlagen der Betriebssystemprogrammierung Präsentation A3, A4, A5, A6 21. März 2013 IAIK Grundlagen der Betriebssystemprogrammierung 1 / 73 1 A3 - Function Pointers 2 A4 - C++: The good, the bad and

More information

Konzepte objektorientierter Programmierung

Konzepte objektorientierter Programmierung Konzepte objektorientierter Programmierung Prof. Dr. Peter Müller Werner Dietl Software Component Technology Exercises 3: Some More OO Languages Wintersemester 04/05 Agenda for Today 2 Homework Finish

More information

Ch 7-1. Object-Oriented Programming and Classes

Ch 7-1. Object-Oriented Programming and Classes 2014-1 Ch 7-1. Object-Oriented Programming and Classes May 10, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;

More information

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk

www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 www.virtualians.pk CS506 Web Design and Development Solved Online Quiz No. 01 Which of the following is a general purpose container? JFrame Dialog JPanel JApplet Which of the following package needs to be import while handling

More information

An Internet Course in Software Development with C++ for Engineering Students

An Internet Course in Software Development with C++ for Engineering Students An Internet Course in Software Development with C++ for Engineering Students Yosef Gavriel, Robert Broadwater Department of Electrical and Computer Engineering Virginia Tech Session 3232 Abstract This

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Chapter 5 Functions. Introducing Functions

Chapter 5 Functions. Introducing Functions Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Chapter 13 - Inheritance

Chapter 13 - Inheritance Goals Chapter 13 - Inheritance To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass constructors To learn about protected and package

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

Computer Programming C++ Classes and Objects 15 th Lecture

Computer Programming C++ Classes and Objects 15 th Lecture Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline

More information

Basic Object-Oriented Programming in Java

Basic Object-Oriented Programming in Java core programming Basic Object-Oriented Programming in Java 1 2001-2003 Marty Hall, Larry Brown http:// Agenda Similarities and differences between Java and C++ Object-oriented nomenclature and conventions

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

Netscape Internet Service Broker for C++ Programmer's Guide. Contents

Netscape Internet Service Broker for C++ Programmer's Guide. Contents Netscape Internet Service Broker for C++ Programmer's Guide Page 1 of 5 [Next] Netscape Internet Service Broker for C++ Programmer's Guide Nescape ISB for C++ - Provides information on how to develop and

More information

Regression Test Selection for Java Software

Regression Test Selection for Java Software Proc. of the ACM Conf. on OO Programming, Systems, Languages, and Applications (OOPSLA ), ACM Copyright. Regression Test Selection for Java Software Mary Jean Harrold harrold@cc.gatech.edu Alessandro Orso

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Programming with Data Types to enhance reliability and productivity (through reuse and by facilitating evolution) Object (instance) State (fields) Behavior (methods) Identity

More information

Class 16: Function Parameters and Polymorphism

Class 16: Function Parameters and Polymorphism Class 16: Function Parameters and Polymorphism SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 16 Fall 2011 1 / 15

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below: http://www.tutorialspoint.com/java/java_methods.htm JAVA - METHODS Copyright tutorialspoint.com A Java method is a collection of statements that are grouped together to perform an operation. When you call

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch13 Inheritance PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for accompanying

More information

Chapter 13 Storage classes

Chapter 13 Storage classes Chapter 13 Storage classes 1. Storage classes 2. Storage Class auto 3. Storage Class extern 4. Storage Class static 5. Storage Class register 6. Global and Local Variables 7. Nested Blocks with the Same

More information

Tutorial on Writing Modular Programs in Scala

Tutorial on Writing Modular Programs in Scala Tutorial on Writing Modular Programs in Scala Martin Odersky and Gilles Dubochet 13 September 2006 Tutorial on Writing Modular Programs in Scala Martin Odersky and Gilles Dubochet 1 of 45 Welcome to the

More information

Inheritance in Programming Languages

Inheritance in Programming Languages Inheritance in Programming Languages Krishnaprasad Thirunarayan Metadata and Languages Laboratory Department of Computer Science and Engineering Wright State University Dayton, OH-45435 INTRODUCTION Inheritance

More information

Friendship and Encapsulation in C++

Friendship and Encapsulation in C++ Friendship and Encapsulation in C++ Adrian P Robson Department of Computing University of Northumbria at Newcastle 23rd October 1995 Abstract There is much confusion and debate about friendship and encapsulation

More information

POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful

POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful POLYTYPIC PROGRAMMING OR: Programming Language Theory is Helpful RALF HINZE Institute of Information and Computing Sciences Utrecht University Email: ralf@cs.uu.nl Homepage: http://www.cs.uu.nl/~ralf/

More information

Conditions & Boolean Expressions

Conditions & Boolean Expressions Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In

More information

LAB4 Making Classes and Objects

LAB4 Making Classes and Objects LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to

More information

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming

More information

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008. 1

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008. 1 Event Driven Simulation in NS2 Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008. 1 Outline Recap: Discrete Event v.s. Time Driven Events and Handlers The Scheduler

More information

Introduction to Programming Block Tutorial C/C++

Introduction to Programming Block Tutorial C/C++ Michael Bader Master s Program Computational Science and Engineering C/C++ Tutorial Overview From Maple to C Variables, Operators, Statements Functions: declaration, definition, parameters Arrays and Pointers

More information

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Test #1 Next Thursday During Class Cover through (near?) end of Chapter 5 Objectives Learn about linked lists Become aware of the basic properties of

More information

Brent A. Perdue. July 15, 2009

Brent A. Perdue. July 15, 2009 Title Page Object-Oriented Programming, Writing Classes, and Creating Libraries and Applications Brent A. Perdue ROOT @ TUNL July 15, 2009 B. A. Perdue (TUNL) OOP, Classes, Libraries, Applications July

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Web development... the server side (of the force)

Web development... the server side (of the force) Web development... the server side (of the force) Fabien POULARD Document under license Creative Commons Attribution Share Alike 2.5 http://www.creativecommons.org/learnmore Web development... the server

More information

17. Friendship and Inheritance

17. Friendship and Inheritance - 117 - Object Oriented Programming: 17. Friendship and Inheritance Friend functions In principle, private and protected members of a class cannot be accessed from outside the same class in which they

More information

AP COMPUTER SCIENCE A 2007 SCORING GUIDELINES

AP COMPUTER SCIENCE A 2007 SCORING GUIDELINES AP COMPUTER SCIENCE A 2007 SCORING GUIDELINES Question 4: Game Design (Design) Part A: RandomPlayer 4 points +1/2 class RandomPlayer extends Player +1 constructor +1/2 public RandomPlayer(String aname)

More information