Motivation Dynamic bindin facilitates more exible and extensible software architectures, e.., { Not all desin decisions need to be known durin the ini

Size: px
Start display at page:

Download "Motivation Dynamic bindin facilitates more exible and extensible software architectures, e.., { Not all desin decisions need to be known durin the ini"

Transcription

1 The C++ Prorammin Lanuae Dynamic Bindin Outline Motivation Dynamic vs. Static Bindin Shape Example Callin Mechanisms Downcastin Run-Time Type Identication Summary Motivation When desinin a system it is often the case that developers: 1. Know what class interfaces they want, without precisely knowin the most suitable representation 2. Know what alorithms they want, without knowin how particular operations should be implemented In both cases, it is often desirable to defer certain decisions as lon as possible { Goal: reduce the eort required to chane the implementation once enouh information is available to make an informed decision 1 2 Motivation Therefore, it is useful to have some form of abstract \place-holder" { Information hidin and data abstraction provide compile-time and link-time place-holders i.e., chanes to representations require recompilin and/or relinkin: :: { Dynamic bindin provides a dynamic place-holder i.e., defer certain decisions until run-time without disruptin existin code structure Note, dynamic bindin is orthoonal to dynamic linkin: :: Dynamic bindin is less powerful than pointersto-functions, but more comprehensible and less error-prone { i.e., since the compiler performs type checkin at compile-time 3 Motivation Dynamic bindin allows applications to be written by invokin eneral methods via a base class pointer, e.., class Base f public: virtual int vf (void); ; Base *bp = /* pointer to a subclass */; bp->vf (); However, at run-time this invocation actually invokes more specialized methods implemented in a derived class, e.., class Derived : public Base f public: virtual int vf (void); ; Derived d; bp = &d; bp->vf (); // invokes Derived::vf() In C++, this requires that both the eneral and specialized methods are virtual functions 4

2 Motivation Dynamic bindin facilitates more exible and extensible software architectures, e.., { Not all desin decisions need to be known durin the initial staes of system development i.e., they may be postponed until run-time { Complete source code is not required to extend the system i.e., only headers and object code This aids both exibility and extensibility { Flexibility = \easily recombine existin components into new conurations" { Extensibility = \easily add new components" Dynamic vs. Static Bindin Inheritance review { A pointer to a derived class can always be used as a pointer to a base class that was inherited publicly Caveats: { e.., 1. The inverse is not necessarily valid or safe 2. Private base classes have dierent semantics: :: template <class T> class Checked Vector : public Vector<T> f :::; Checked Vector<int> cv (20); Vector<int> *vp = &cv; int elem = (*vp)[0]; // calls operator[] (int) { A question arises here as to which version of operator[] is called? 5 6 Dynamic vs. Static Bindin The answer depends on the type of bindin used: :: 1. Static Bindin: the compiler uses the type of the pointer to perform the bindin at compile time. Therefore, Vector::operator[] will be called Vector::operator[](vp, 0); 2. Dynamic Bindin: the decision is made at runtime based upon the type of the actual object. Checked Vector::operator[] will be called in this case (*vp->vptr[1])(vp, 0); Quick quiz: how must class Vector be chaned to switch from static to dynamic bindin? Dynamic vs. Static Bindin When to chose use dierent bindins { Static Bindin Use when you are sure that any subsequent derived classes will not want to override this operation dynamically (just redene/hide) Use mostly for reuse or to form \concrete data types" { Dynamic Bindin Use when the derived classes may be able to provide a dierent (e.., more functional, more ecient) implementation that should be selected at run-time Used to build dynamic type hierarchies and to form \abstract data types" 7 8

3 Dynamic vs. Static Bindin Eciency vs. exibility are the primary tradeos between static and dynamic bindin Static bindin is enerally more ecient since 1. It has less time and space overhead 2. It also enables function inlinin Dynamic bindin is more exible since it enables developers to extend the behavior of a system transparently { However, dynamically bound objects are dicult to store in shared memory Dynamic Bindin in C++ In C++, dynamic bindin is sinaled by explicitly addin the keyword virtual in a method declaration, e.., struct Base f virtual int vf1 (void) f cout << "hello\n"; int f1 (void); ; Note, virtual functions must be class methods, i.e., they cannot be: { Ordinary \stand-alone" functions { Class data { Static methods Other lanuaes (e.., Eiel) make dynamic bindin the default: :: { This is more exible, but may be less ecient 9 10 Dynamic Bindin in C++ Virtual functions: { These are methods with a xed callin interface, where the implementation may chane in subsequent derived classes, e.., struct Derived 1 : public Base f virtual int vf1 (void) f cout << "world\n"; ; { Supplyin the virtual keyword is optional when overridin vf1 in derived classes, e.., struct Derived 2 : public Derived 1 f // Still a virtual: :: int vf1 (void) f cout << "hello world\n"; int f1 (void); // not virtual ; { Note, you can declare a virtual function in any derived class, e.., struct Derived 3 : public Derived 2 f virtual int vf2 (int); // dierent from vf1! virtual int vf1 (int); // Be careful!!!! 11 Dynamic Bindin in C++ Virtual functions : { The virtual function dispatch mechanism uses the \dynamic type" of an object (identied by a reference or pointer) to select the appropriate method that is invoked at run-time The selected method will depend on the class of the object bein pointed at and not on the pointer type { e.., void foo (Base *bp) f bp->vf1 (); // virtual function Base b; Base *bp = &b; bp->vf1 (); // prints "hello" Derived 1 d; bp = &d; bp->vf1 (); // prints "world" foo (&b); // prints "hello" foo (&d); // prints "world" 12

4 Dynamic Bindin in C++ Virtual functions : { Virtual methods are dynamically bound and dispatched at run-time, usin an index into an array of pointers to class methods Note, this requires only constant overhead, reardless of the inheritance hierarchy depth: :: The virtual mechanism is set up by the constructor(s), which may stack several levels { e.., deep: :: void foo (Base *bp) f bp->vf1 (); // Actual call // (*bp->vptr[1])(bp); { Usin virtual functions adds a small amount of time and space overhead to the class/object size and method invocation time Shape Example The canonical dynamic bindin example: { Describin a hierarchy of shapes in a raphical user interface library { e.., Trianle, Square, Circle, Rectanle, Ellipse, etc. A conventional C or Ada solution would 1. Use a union or variant record to represent a Shape type 2. Have a type ta in every Shape object 3. Place special case checks in functions that operate on Shapes { e.., functions that implement operations like rotation and drawin C or Ada solution { e.., typedef struct Shape Shape; struct Shape f enum f CIRCLE, SQUARE, TRIANGLE, RECTANGLE /* Extensions o here: ::. */ type ; union f struct Circle f /* :::. */ c ; struct Square f /* :::. */ s ; struct Trianle f /* :::. */ t ; struct Rectanle f /* :::. */ r ; u ; ; void rotate shape (Shape *sp, double derees) f switch (sp->type ) f case CIRCLE: return; case SQUARE: // Don't foret to break! // ::: 15 Problems with the conventional approach: { It is dicult to extend code desined this way: e.., chanes are associated with functions and alorithms Which are often \unstable" elements in a software system desin and implementation Therefore, modications will occur in portions of the code that switch on the type ta Usin a switch statement causes problems, e.., Settin and checkin type tas Fallin throuh to the next case, etc: :: Note, Eiel disallows switch statements to prevent these problems! 16

5 Problems with the conventional approach : { Data structures are \passive" i.e., functions do most of processin work on dierent kinds of Shapes by explicitly accessin the appropriate elds in the object This lack of information hidin aects maintainability { Solution wastes space by makin worst-case assumptions wrt structs and unions { Must have source code to extend the system in a portable, maintainable manner An object-oriented solution uses inheritance and dynamic bindin to derive specic shapes (e.., Circle, Square, Rectanle, and Trianle) from a eneral Abstract Base Class (ABC) called Shape This approach facilities a number of software quality factors: 1. Reuse 2. Transparent extensibility 3. Delayin decisions until run-time 4. Architectural simplicity /* Abstract Base Class and Derived Classes for Shape */ class Shape f public: Shape (double x, double y, Color &c) : center (Point (x, y)), color (c) f Shape (Point &p, Color &c) : center (p), color (c) f virtual int rotate (double derees) = 0; virtual int draw (Screen &) = 0; virtual ~Shape (void) = 0; void chane color (Color &c) f this->color = c; Point where (void) const f return this->center ; void move (Point &to) f this->center = to; Note, the \OOD challene" is to map arbitrarily complex system architectures into inheritance hierarchies private: Point center ; Color color ; ; 19 20

6 Abstract Base Classes (ABCs) Note, certain methods only make sense on subclasses of class Shape { e.., Shape::rotate and Shape::draw Therefore, class Shape is dened as an Abstract Base Class { Essentially denes only the class interface { Derived (i.e., concrete) classes may provide multiple, dierent implementations 1. ABCs support the notion of a eneral concept (e.., Shape) of which only more concrete object variants (e.., Circle and Square) are actually used 2. ABCs are only used as a base class for subsequent derivations { Therefore, it is illeal to create objects of ABCs However, it is leal to declare pointers or references to such objects: :: { ABCs force denitions in subsequent derived classes for undened methods In C++, an ABC is created by denin a class with at least one \pure virtual function" { Compare with deferred classes in Eiel: :: Pure virtual functions { Pure virtual functions must be methods { They are dened in the base class of the inheritance hierarchy, and are often never intended to be invoked directly i.e., they are simply there to tie the inheritance hierarchy toether by reservin a slot in the virtual table: :: { Therefore, C++ allows users to specify \pure virtual functions" Usin the pure virtual specier = 0 indicates methods that are not meant to be dened in that class Note, pure virtual functions are automatically inherited: :: Side note reardin pure virtual destructors { The only eect of declarin a pure virtual destructor is to cause the class bein dened to be an ABC { Destructors are not inherited, therefore: A pure virtual destructor in a base class will not force derived classes to be ABCs Nor will any derived class be forced to declare a destructor { Furthermore, you will have to provide a denition (i.e., write the code for a method) for the pure virtual destructor in the base class Otherwise you will et run-time errors! 23 24

7 The C++ solution to the Shapes example uses inheritance and dynamic bindin { In C++, the special case code is associated with the derived class data structures { e.., class Circle : public Shape f public: Circle (Point &p, double rad); virtual void draw (Screen &); virtual void rotate (double derees) f // ::: private: double radius ; ; class Rectanle : public Shape f public: Rectanle (Point &p, double l, double w); virtual void rotate (double derees); virtual void draw (Screen &); // ::: private: double lenth, width ; ; 25 C++ solution { Usin the special relationship between base classes and derived subclasses, any Shape * can now be \rotated" without worryin about what kind of Shape it points to { The syntax for doin this is: void rotate shape (Shape *sp, double derees) f sp->rotate (derees); // (*sp->vptr[1]) (sp, derees); { Note, we are still \interface compatible" with oriinal C version! 26 Characteristics of the C++ dynamic bindin solution: vtable (Circle) vtable (Rectanle) { Associate all specializations with the derived class 0 Rotate Draw 0 Rotate Draw Rather than with function rotate shape vptr Circle vptr Rectanle { This makes it possible to add new types (derived from base class Shape) without breakin existin code i.e., most extensions/chanes occur in only one place This code will continue to work reardless of what derived class of Shape that sp actually points to, e.., Circle c; Rectanle r; rotate shape (&c, 100.0); rotate shape (&r, 250.0); 27 { e.., add a new class Square derived from class Rectanle: class Square : public Rectanle f // Inherits lenth and width from Rectanle public: Square (Point &p, double base); virtual void draw (Screen &); virtual void rotate (double deree) f if (deree % 90.0!= 0) // Reuse existin code Rectanle::rotate (deree); /* :::. */ ; 28

8 C++ solution with dynamic bindin { We can still rotate any Shape object by usin the oriinal function, i.e., void rotate shape (Shape *sp, double derees) f sp->rotate (derees); Square s; Circle c; Rectanle r; rotate shape (&s, 100.0); rotate shape (&r, 250.0); rotate shape (&c, 17.0); Comparison between 2 approaches { If support for Square was added in the C or Ada solution, then every place where the type ta was accessed would have to be modied i.e., modications are spread out all over the place Includin both header les and functions Note, the C or Ada approach prevents extensibility if the provider of Square does not have access to the source code of function rotate shape! { i.e., only the header les and object code is required to allow extensibility in C Comparison between 2 approaches /* C solution */ void rotate shape (Shape *sp, double deree) f switch (sp->type ) f case CIRCLE: return; case SQUARE: if (deree % 90 == 0) return; else /* FALLTHROUGH */; case RECTANGLE: // ::: break; Example function that rotates size shapes by anle derees: void rotate all (Shape *vec[], int size, double anle) f for (int i = 0; i < size; i++) vec[i]->rotate (anle); vec[i]->rotate (anle) is a virtual function call { It is resolved at run-time accordin to the actual type of object pointed to by vec[i] { i.e., vec[i]->rotate (anle) becomes (*vec[i]->vptr[1]) (vec[i], anle); 31 32

9 Sample usae of function rotate all is Shape *shapes[] = f new Circle (/* :::. */), new Square (/* :::. */) ; int size = sizeof shapes / sizeof *shapes; rotate all (shapes, size, 98.6); vtable (Circle) 0 Rotate Draw 0 Rotate Draw vptr Circle vtable (Square) vptr Square Note, it is not enerally possible to know the exact type of elements in variable shapes until run-time { However, at compile-time we know they are all derived subtypes of base class Shape shapes 0 1 This is why C++ is not fully polymorphic, but is stronly typed Here's what the memory layout looks like Callin Mechanisms Note that both the inheritance/dynamic bindin and union/switch statement approaches provide mechanisms for handlin the desin and implementation of variants The appropriate choice of techniques often depends on whether the class interface is stable or not { Addin a new subclass is easy via inheritance, but dicult usin union/switch (since code is spread out everywhere) { On the other hand, addin a new function to an inheritance hierarchy is dicult, but relatively easier usin union/switch (since the code for the function is localized) Given a pointer to a class object (e.., class Foo *ptr) how is the method call ptr->f (ar) resolved? There are three basic approaches: 1. Static Bindin 2. Virtual Function Tables 3. Method Dispatch Tables C++ and Java use both static bindin and virtual function tables. Smalltalk and Objective C use method dispatch tables Note, type checkin is orthoonal to bindin time: :: 35 36

10 Callin Mechanisms Static Bindin { Method f's address is determined at compile/link time { Provides for stron type checkin, completely checkable/resolvable at compile time { Main advantae: the most ecient scheme e.., it permits inline function expansion { Main disadvantae: the least exible scheme Callin Mechanisms Virtual Function Tables { Method f is converted into an index into a table of pointers to functions (i.e., the virtual function table) that permit run-time resolution of the callin address The *ptr object keeps track of its type via a hidden pointer (vptr) to its associated virtual function table (vtable) { Virtual functions provide an exact specication of the type sinature The user is uaranteed that only operations specied in class declarations will be accepted by the compiler Callin Mechanisms Callin Mechanisms Virtual Function Tables { Main advantaes 1. More exible than static bindin vptr obj 1 f1 f2 vtable There only a constant amount of overhead (compared with method dispatchin) e.., in C++, pointers to functions are stored in a separate table, not in the object! { Main disadvantaes Less ecient e.., often not possible to inline the virtual function calls: :: 39 e.., vptr obj 2 class Foo f public: virtual int f1 (void); virtual int f2 (void); int f3 (void); private: // data ::: ; Foo obj 1, obj 2, obj 3; vptr obj 3 40

11 Callin Mechanisms Method Dispatch Tables { Method f is looked up in a table that is created and manaed dynamically at run-time i.e., add/delete/chane methods dynamically { Main advantae: the most exible scheme i.e., new methods can be added or deleted on-the-y and allows users to invoke any method for any object { Main disadvantae: enerally inecient and not always type-secure May require searchin multiple tables at runtime Some form of cachin is often used Performin run-time type checkin alon with run-time method invocation further decreases run-time eciency Type errors may not manifest themselves until run-time 41 Downcastin Downcastin is dened as: { Either manually or automatically castin a pointer or reference of a base class type to a type of a pointer or reference to a derived class. { i.e., oin the opposite direction from usual \base-class/derived-class" inheritance relationships: :: Downcastin is useful for 1. Clonin an object { e.., required for \deep copies" 2. Restorin an object from disk { This is hard to do transparently: :: 3. Takin an object out of a heteroeneous collection of objects and restorin its oriinal type { Also hard to do, unless the only access is via the interface of the base class 42 Downcastin Contravariance { Downcastin can lead to trouble due to contravariance Downcastin It is consequence of inheritance that works aainst prorammers in a symmetrically opposin fashion to the way inheritance works for them dp bp { Consider the followin derivation hierarchy: b i d i struct Base f int i ; virtual int foo (void) f return this->i ; ; struct Derived : public Base f int j ; virtual int foo (void) f return this->j ; ; void foo (void) f Base b; Derived d; Base *bp = &d; // OK, a Derived is a Base Derived *dp = &b;// Error, a Base is not // necessarily a Derived 43? j is refer- Problem: what happens if dp->j enced or set? 44

12 Downcastin Contravariance { Since a Derived object always contains a Base part certain operations are well dened: bp = &d; bp->i = 10; bp->foo (); // calls Derived::foo (); { However, since base objects do not contain the data portions of any of their derived classes, other operations are not dened e.., this assinment accesses information beyond the end of object b: dp = (Derived *) &b; dp->j = 20; // bi trouble! { Note, C++ permits contravariance if the prorammer explicitly provides a downcast, e.., dp = (Derived *) &b; // unchecked cast { It is the prorammer's responsibility to make sure that operations upon dp don't access nonexistent elds or methods 45 Downcastin Traditionally, downcastin was necessary due to the fact that C++ oriinally did not support overloadin on function \return" type { e.., in C++ the followin is currently not allowed in most compilers: struct Base f virtual Base *clone (void); ; struct Derived : public Base f virtual Derived *clone (void); // Error! ; { However, assumin we make the appropriate virtual Base *clone (void) chane in class Derived: :: Base *ob1 = new Derived; Derived *ob2 = new Derived; { The followin are syntax \errors" (thouh they are actually type-secure): Derived *ob3 = ob1->clone (); // error Derived *ob4 = ob2->clone (); // error { To perform the intended operation, we must use a cast to \trick" the type system, e.., Derived *ob5 = (Derived *) ob1->clone (); 46 Downcastin The riht way to handle this is to use the C++ Run-Time Type Identication (RTTI) feature However, since most C++ compilers do not support type-safe downcastin, some workarounds include: 1. Don't do it, since it is potentially non-type-safe 2. Use an explicit cast (e.., ob5) and cross your ners 3. Encode type ta and write massive switch statements { Which defeats the purpose of dynamic bindin Run-Time Type Identication RTTI is a technique that allows applications to use the C++ run-time system to query the type of an object at run-time { Only supports very simple queries reardin the interface supported by a type RTTI is only fully supported for dynamicallybound classes { Alternative approaches would incur unacceptable run-time costs and storae layout compatibility problems 4. Manually encode the return type into the method name: Derived *ob6 = ob2->clonederived (); 47 48

13 Run-Time Type Identication RTTI could be used in our oriinal example involvin ob1 Base *ob1 = new Derived; if (Derived *ob2 = dynamic cast<derived *>(ob1->clone ())) /* use ob2 */; else /* error! */ For a dynamic cast to succeed, the \actual type" of ob1 would have to either be a Derived object or some subclass of Derived { If the types do not match the operation fails at run-time { If failure occurs, there are several ways to dynamically indicate this to the application: To return a NULL pointer for failure To throw an exception e.., in the case of reference casts: :: Run-Time Type Identication dynamic cast used with references { A reference dynamic cast that fails throws a bad cast exception e.., void clone (Base &ob1) f try f Derived &ob2 = dynamic cast<derived &>(ob1); /* :::*/ catch (bad cast) f /* :::*/ Run-Time Type Identication Alon with the dynamic cast extension, the C++ lanuae now contains a typeid operator that allows queries of a limited amount of type information at run-time { Includes both dynamically-bound and non-dynamicallybound types: :: e.., typeid (type name)! const Type info & typeid (expression)! const Type info & Note that the expression form returns the run-time type of the expression if the class is dynamically bound: :: Run-Time Type Identication Here are some short examples Base *bp = new Derived; Base &br = *bp; typeid (bp) == typeid (Base *) // true typeid (bp) == typeid (Derived *) // false typeid (bp) == typeid (Base) // false typeid (bp) == typeid (Derived) // false typeid (*bp) == typeid (Derived) // true typeid (*bp) == typeid (Base) // false typeid (br) == typeid (Derived) // true typeid (br) == typeid (Base) // false typeid (&br) == typeid (Base *) // true typeid (&br) == typeid (Derived *) // false 51 52

14 Run-Time Type Identication A common ripe is RTTI will encourae the dreaded \switch statement of death," e.., void foo (Object *op) f op->do somethin (); if (Foobar *fbp = dynamic cast<foobar *> (op)) fbp->do foobar thins (); else if (Foo *fp = dynamic cast<foo *> (op)) fp->do foo thins (); else if (Bar *bp = dynamic cast<bar *> (op)) bp->do bar thins (); else op->do object stu (); Implementin this style of type tain by hand (rather than by the compiler) leads to an alternative, slower method of dispatchin methods { i.e., duplicatin the work of vtables in an unsafe manner that a compiler cannot double check { However, even an automated approach can be hard to make ecient! Summary Dynamic bindin enables applications and developers to defer certain implementation decisions until run-time { i.e., which implementation is used for a particular interface It also facilitates a decentralized architecture that promotes exibility and extensibility { e.., it is possible to modify functionality without modifyin existin code There is some additional run-time overhead from usin dynamic bindin: :: { However, alternative solutions also incur overhead e.., the union/switch approach 53 54

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

Pointers to Functions Pointers to functions are a surprisinly useful and frequently underutilized feature of C and C++. Pointers to functions provide

Pointers to Functions Pointers to functions are a surprisinly useful and frequently underutilized feature of C and C++. Pointers to functions provide The C++ Prorammin Lanuae Pointers to Member Functions Outline Pointers to Functions Pointers to Member Functions The Type of a Class Member Declarin a Pointer to Member Function Pointer to Class Member

More information

Tips for C Prorammers Use const instead of #dene to declare proram constants, e.., { C #dene PI #dene MAX INT 0x7FFFFFFF #dene MAX UNSIGNED 0x

Tips for C Prorammers Use const instead of #dene to declare proram constants, e.., { C #dene PI #dene MAX INT 0x7FFFFFFF #dene MAX UNSIGNED 0x The C++ Prorammin Lanuae C++ Tips and Traps Outline Tips for C Prorammers C++ Traps and Pitfalls Eciency and Performance 1 Tips for C Prorammers Use const instead of #dene to declare proram constants,

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

Data Abstraction. Hwansoo Han

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

More information

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

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

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

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

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

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

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

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE 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

More information

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

Object-oriented Programming. Object-oriented Programming

Object-oriented Programming. Object-oriented Programming 2014-06-13 Object-oriented Programming Object-oriented Programming 2014-06-13 Object-oriented Programming 1 Object-oriented Languages object-based: language that supports objects class-based: language

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

The Compositional C++ Language. Denition. Abstract. This document gives a concise denition of the syntax and semantics

The Compositional C++ Language. Denition. Abstract. This document gives a concise denition of the syntax and semantics The Compositional C++ Language Denition Peter Carlin Mani Chandy Carl Kesselman March 12, 1993 Revision 0.95 3/12/93, Comments welcome. Abstract This document gives a concise denition of the syntax and

More information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

More information

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading How C++ Works 1 Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++

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

The SpecC Methodoloy Technical Report ICS December 29, 1999 Daniel D. Gajski Jianwen Zhu Rainer Doemer Andreas Gerstlauer Shuqin Zhao Department

The SpecC Methodoloy Technical Report ICS December 29, 1999 Daniel D. Gajski Jianwen Zhu Rainer Doemer Andreas Gerstlauer Shuqin Zhao Department The SpecC Methodoloy Technical Report ICS-99-56 December 29, 1999 Daniel D. Gajski Jianwen Zhu Rainer Doemer Andreas Gerstlauer Shuqin Zhao Department of Information and Computer Science University of

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

15: Polymorphism & Virtual Functions

15: Polymorphism & Virtual Functions 15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions

More information

Short Notes of CS201

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

More information

ECE 3574: Dynamic Polymorphism using Inheritance

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

More information

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

C++ Yanyan SHEN. slide 1

C++ Yanyan SHEN. slide 1 C++ Yanyan SHEN slide 1 History C++ is an object-oriented extension of C Designed by Bjarne Stroustrup at Bell Labs His original interest at Bell Labs was research on simulation Early extensions to C are

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

Object typing and subtypes

Object typing and subtypes CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3 Subtyping and Inheritance Interface The

More information

Subtyping (Dynamic Polymorphism)

Subtyping (Dynamic Polymorphism) Fall 2018 Subtyping (Dynamic Polymorphism) Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References PFPL - Chapter 24 Structural Subtyping - Chapter 27 Inheritance TAPL (pdf) - Chapter

More information

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading HOW C++ WORKS Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++

More information

CSE 307: Principles of Programming Languages

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

More information

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

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

G52CPP C++ Programming Lecture 13

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

More information

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1 Object-Oriented Languages and Object-Oriented Design Ghezzi&Jazayeri: OO Languages 1 What is an OO language? In Ada and Modula 2 one can define objects encapsulate a data structure and relevant operations

More information

G52CPP C++ Programming Lecture 12

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

More information

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

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 Preview Inheritance Example: Ada-style Vectors Dynamic Bindin Preview Overloadin New-Style Comments Type-Safe Linkae Inline Functions Dyna

Inheritance Preview Inheritance Example: Ada-style Vectors Dynamic Bindin Preview Overloadin New-Style Comments Type-Safe Linkae Inline Functions Dyna The C++ Prorammin Lanuae A Tour Throuh C++ Outline C++ Overview C++ Desin Goals Major C++ Enhancements Other Enhancements Lanuae Features Not Part of C++ Function Prototypes C++ Classes Class Vector Example

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

Object Oriented Programming. Spring 2008

Object Oriented Programming. Spring 2008 Dynamic Binding Implementation Object Oriented Programming 236703 Spring 2008 1 Implementation of Virtual Functions class Ellipse { //... public: E 1 virtual void draw() const; draw E + virtual void hide()

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

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

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

September 10,

September 10, September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible

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

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers Resource Management Resource Management With a Unique Pointer Dynamic memory is an example of a resource that is allocated and must be released. void f() { Point* p = new Point(10, 20); // use p delete

More information

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

Department of Computer Science, University of Utah. 1 Introduction

Department of Computer Science, University of Utah. 1 Introduction International Conference on Computer Systems and Education, IISc, Banalore, 1994 Type-safe Composition of Object Modules Guruduth Banavar, Gary Lindstrom, Doulas Orr Department of Computer Science, University

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

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

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

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

More information

History C++ Design Goals. How successful? Significant constraints. Overview of C++

History C++ Design Goals. How successful? Significant constraints. Overview of C++ 1 CS 242 History C++ John Mitchell C++ is an object-oriented extension of C C was designed by Dennis Ritchie at Bell Labs used to write Unix based on BCPL C++ designed by Bjarne Stroustrup at Bell Labs

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism http://en.wikipedia.org/wiki/encapsulation_(object-oriented_programming)

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

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

Week 7. Statically-typed OO languages: C++ Closer look at subtyping C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula

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

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

Pizza ëordersky 1997ë. However, we felt that Pizza èand other similar lanuaesè suered from one fault that we had taken pains to avoid in the oriinal d

Pizza ëordersky 1997ë. However, we felt that Pizza èand other similar lanuaesè suered from one fault that we had taken pains to avoid in the oriinal d Multiparadim Extensions to Java Timothy A.Budd Department of Computer Science Oreon State University Corvallis, Oreon, USA November 1, 2000 Abstract In 1995 my students and I developed Leda, a multiparadim

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

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

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

More information

ICC++ Language Denition. Andrew A. Chien and Uday S. Reddy 1. May 25, 1995

ICC++ Language Denition. Andrew A. Chien and Uday S. Reddy 1. May 25, 1995 ICC++ Language Denition Andrew A. Chien and Uday S. Reddy 1 May 25, 1995 Preface ICC++ is a new dialect of C++ designed to support the writing of both sequential and parallel programs. Because of the signicant

More information

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ 1 Overloading, Overriding POLYMORPHISM poly morphos many forms Overloading single method name having several alternative implementations. Overriding child class provides

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics 1 What do you mean by axiomatic Knowledge C254.1 semantics? Give the weakest precondition for a sequence of statements.

More information

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

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

More information

Chapter 9 :: Data Abstraction and Object Orientation

Chapter 9 :: Data Abstraction and Object Orientation Chapter 9 :: Data Abstraction and Object Orientation Programming Language Pragmatics Michael L. Scott Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it in

More information

Lecturer: William W.Y. Hsu. Programming Languages

Lecturer: William W.Y. Hsu. Programming Languages Lecturer: William W.Y. Hsu Programming Languages Chapter 9 Data Abstraction and Object Orientation 3 Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though

More information

Francesco Nidito. Programmazione Avanzata AA 2007/08

Francesco Nidito. Programmazione Avanzata AA 2007/08 Francesco Nidito Programmazione Avanzata AA 2007/08 Outline 1 2 3 4 Reference: Micheal L. Scott, Programming Languages Pragmatics, Chapter 10 , type systems and type checking A type type is an abstraction

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance

More information

Francesco Nidito. Programmazione Avanzata AA 2007/08

Francesco Nidito. Programmazione Avanzata AA 2007/08 Francesco Nidito Programmazione Avanzata AA 2007/08 Outline 1 2 3 4 Reference: Micheal L. Scott, Programming Languages Pragmatics, Chapter 10 , type systems and type checking A type type is an abstraction

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

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

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

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

C++ Modern and Lucid C++ for Professional Programmers Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Inheritance and dynamic Polymorphism base classes,

More information

Contract Programming For C++0x

Contract Programming For C++0x Contract Programming For C++0x WG21/N1800 and J16/05-0060 Lawrence Crowl and Thorsten Ottosen lawrence.crowl@sun.com and nesotto@cs.aau.dk 2005-04-27 Overview This is an annotated version of the presentation

More information

CCured. One-Slide Summary. Lecture Outline. Type-Safe Retrofitting of C Programs

CCured. One-Slide Summary. Lecture Outline. Type-Safe Retrofitting of C Programs CCured Type-Safe Retrofitting of C Programs [Necula, McPeak,, Weimer, Condit, Harren] #1 One-Slide Summary CCured enforces memory safety and type safety in legacy C programs. CCured analyzes how you use

More information

Advanced Systems Programming

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

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism. Outline Inheritance Class Extension Overriding Methods Inheritance and Constructors Polymorphism Abstract Classes Interfaces 1 OOP Principles Encapsulation Methods and data are combined in classes Not

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

Objects, Encapsulation, Inheritance (2)

Objects, Encapsulation, Inheritance (2) CS 242 2012 Objects, Encapsulation, Inheritance (2) Reading (two lectures) Chapter 10, except section 10.4 Chapter 11, sections 11.1, 11.2, 11.3.1 and 11.4., 11.5, 11.6 only Chapter 12, sections 12.1,

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

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

Outline. Computer Science 331. Information Hiding. What This Lecture is About. Data Structures, Abstract Data Types, and Their Implementations

Outline. Computer Science 331. Information Hiding. What This Lecture is About. Data Structures, Abstract Data Types, and Their Implementations Outline Computer Science 331 Data Structures, Abstract Data Types, and Their Implementations Mike Jacobson 1 Overview 2 ADTs as Interfaces Department of Computer Science University of Calgary Lecture #8

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. All Rights Reserved. 1 Standard Behavior: When the compiler is working out which member function to call, it selects according to the type of

More information

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc. Chapter 13 Object Oriented Programming Contents 13.1 Prelude: Abstract Data Types 13.2 The Object Model 13.4 Java 13.1 Prelude: Abstract Data Types Imperative programming paradigm Algorithms + Data Structures

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.

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

G Programming Languages - Fall 2012

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

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Declarative Specialization of Object-Oriented Programs

Declarative Specialization of Object-Oriented Programs INSTITUT NATIONAL DE RECHERCHE EN INFORMATIQUE ET EN AUTOMATIQUE Declarative Specialization of Object-Oriented Prorams Euen N. Volanschi, Charles Consel, Gilles Muller, Crispin Cowan N 3118 Février 1997

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information