C++ Yanyan SHEN. slide 1

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

Objects, Encapsulation, Inheritance (2)

Subtyping (Dynamic Polymorphism)

Object typing and subtypes

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

Data Abstraction. Hwansoo Han

Thanks! Review. Course Goals. General Themes in this Course. There are many programming languages. Teaching Assistants. John Mitchell.

The Java Programming Language

Procedure and Object- Oriented Abstraction

C++ Important Questions with Answers

C++ Part 2 <: <: C++ Run-Time Representation. Smalltalk vs. C++ Dynamic Dispatch. Smalltalk vs. C++ Dynamic Dispatch

VIRTUAL FUNCTIONS Chapter 10

Advanced oo concepts Specialization of behaviour? Multiple inheritance - alternatives to. Inner classes Classes

Compiler construction 2009

G Programming Languages - Fall 2012

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

CSE 401/M501 Compilers

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

CPS 506 Comparative Programming Languages. Programming Language

Polymorphism Part 1 1

Tokens, Expressions and Control Structures

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

Chapter 5 Object-Oriented Programming

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

September 10,

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

CS-202 Introduction to Object Oriented Programming

Programming Languages: OO Paradigm, Polymorhism and Class Members

Conformance. Object-Oriented Programming Spring 2015

Types and Classes. I II From predefined (simple) and user-defined (composite) types via Abstract data types

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

What about Object-Oriented Languages?

Object-oriented Programming. Object-oriented Programming

Exceptions and Continuations. Lecture #19: More Special Effects Exceptions and OOP. Approach II: Non-Standard Return. Approach I: Do Nothing

COMP322 - Introduction to C++

COMP 2355 Introduction to Systems Programming

Type Analysis. Type Checking vs. Type Inference

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

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 2: Review of Object Orientation

Method Resolution Approaches. Dynamic Dispatch

CS558 Programming Languages Winter 2013 Lecture 8

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

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Lecture 23: Object Lifetime and Garbage Collection

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

Separate compilation. Topic 6: Runtime Environments p.1/21. CS 526 Topic 6: Runtime Environments The linkage convention

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

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

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

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation

Inheritance, Polymorphism and the Object Memory Model

Object Oriented Programming. Solved MCQs - Part 2

Chapter 10 :: Data Abstraction and Object Orientation

Objects. Deian Stefan (Adopted from my & Edward Yang s CS242 slides)

Lecture Notes on Programming Languages

Chapter 9 :: Data Abstraction and Object Orientation

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

Operator Dot Wording

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

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

CS153: Compilers Lecture 11: Compiling Objects

Last Class: Multiple Inheritance. Implementing Polymorphism. Criteria. Problem. Smalltalk Message Passing. Smalltalk

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

What is Inheritance?

Java Object Oriented Design. CSC207 Fall 2014

CMSC 132: Object-Oriented Programming II

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

Chapter 1: Object-Oriented Programming Using C++

What are the characteristics of Object Oriented programming language?

Introducing C++ David Chisnall. March 15, 2011

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

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

CSc 520. Principles of Programming Languages 45: OO Languages Introduction

Object Oriented Programming in C++ Basics of OOP

C++ Inheritance and Encapsulation

COURSE 2 DESIGN PATTERNS

Practice for Chapter 11

QUIZ Friends class Y;

An Introduction to C++

Ch. 10: Name Control

Derived Classes in C++

Outline. Central concepts in OO languages Objects as activation records (Simula) Dynamically-typed object-oriented languages

Intermediate Formats. for object oriented languages

Object Oriented Issues in VDM++

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Lecturer: William W.Y. Hsu. Programming Languages

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

Intermediate Formats. for object oriented languages

Programming Languages Third Edition. Chapter 7 Basic Semantics

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

A Short Summary of Javali

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

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

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Introduction to C++ with content from

CSE 307: Principles of Programming Languages

Lecture 10: building large projects, beginning C++, C++ and structs

Object-Oriented Programming, Iouliia Skliarova

Transcription:

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 based primarily on Simula Called C with classes in early 1980s Features were added incrementally Classes, templates, exceptions, multiple inheritance, type tests... slide 2

Design Goals Provide object-oriented features in C-based language, without compromising efficiency Backwards compatibility with C Better static type checking Data abstraction Objects and classes Prefer efficiency of compiled code where possible Important principle If you do not use a feature, your compiled code should be as efficient as if the language did not include the feature slide 3

How Successful? Many users, tremendous popular success Given the design goals and constraints, very well-designed language Very complicated design, however Many features with complex interactions Difficult to predict from basic principles Most serious users chose subset of language Full language is complex and unpredictable Many implementation-dependent properties slide 4

Significant Constraints C has specific machine model Access to underlying architecture No garbage collection Consistent with the goal of efficiency Need to manage object memory explicitly Local variables stored in activation records Objects treated as generalization of structs Objects may be allocated on stack Stack/heap difference is visible to programmer slide 5

Non-Object-Oriented Additions Function templates (generic programming) Pass-by-reference User-defined overloading slide 6

C++ Object System Classes Objects With dynamic lookup of virtual functions Inheritance Single and multiple inheritance Public and private base classes Subtyping Tied to inheritance mechanism Encapsulation slide 7

Good Decisions Public, private, protected levels of visibility Public: visible everywhere Protected: within class and subclass declarations Private: visible only in class where declared Friend functions and classes Careful attention to visibility and data abstraction Allow inheritance without subtyping Private and protected base classes Useful to separate subtyping and inheritance slide 8

Problem Areas Casts Lack of garbage collection Objects allocated on stack Better efficiency, interaction with exceptions BUT assignment works badly, possible dangling ptrs Overloading Too many code selection mechanisms? Multiple inheritance Efforts at efficiency lead to complicated behavior slide 9

Sample Class: Points class Pt { public: Pt(int xv); Pt(Pt* pv); int getx(); virtual void move(int dx); protected: void setx(int xv); private: int x; }; Overloaded constructor Public read access to private data Virtual function Protected write access Private member data slide 10

Virtual Functions Virtual member functions Accessed by indirection through pointer in object May be redefined in derived subclasses The exact function to call determined dynamically Non-virtual functions are ordinary functions Cannot redefine in subclasses (but can overload) Member functions are virtual if explicitly declared or inherited as virtual, else non-virtual Pay overhead only if you use virtual functions slide 11

Sample Derived Class: Color Point class ColorPt: public Pt { public: ColorPt(int xv,int cv); ColorPt(Pt* pv,int cv); ColorPt(ColorPt* cp); int getcolor(); virtual void move(int dx); virtual void darken(int tint); protected: void setcolor(int cv); private: int color; }; Public base class gives supertype Overloaded constructor Non-virtual function Virtual functions Protected write access Private member data slide 12

Run-Time Representation Point object Point vtable Code for move vptr x 3 ColorPoint object ColorPoint vtable Code for move vptr x c 5 blue Extra level of indirection when function is called Code for darken Data at same offset Function pointers at same offset slide 13

Why Is C++ Lookup Simpler? C++ type gives compiler some superclass Offset of data, function pointers is the same in subclass and superclass, thus known at compile-time Code p->move(x) compiles to equivalent of (*(p->vptr[0]))(p,x) if move is first function in vtable data passed to member function slide 15

Looking Up Methods (1) Point object Point vtable Code for move vptr x 3 ColorPoint object ColorPoint vtable Code for move vptr x c 5 blue Code for darken Point p = new Pt(3); p->move(2); // Compiles to equivalent of (*(p->vptr[0]))(p,2) slide 16

Looking Up Methods (2) Point object Point vtable Code for move vptr x 3 ColorPoint object ColorPoint vtable Code for move vptr x c 5 blue darken() Code for darken Point cp = new ColorPt(5,blue); cp->move(2); What is this for? // Compiles to equivalent of (*(cp->vptr[0]))(cp,2) slide 17

Calls to Virtual Functions One member function may call another class A { public: virtual int f (int x); virtual int g(int y); }; int A::f(int x) { g(i) ;} How does body of f call the right g? If g is redefined in derived class B, then inherited f must call B::g slide 18

This Pointer Code is compiled so that member function takes object itself as first argument Code compiled as int A::f(int x) { g(i) ;} int A::f(A *this, int x) { this->g(i) ;} this pointer may be used in member function Can be used to return pointer to object itself, pass pointer to object itself to another function, etc. slide 19

Non-Virtual Functions How is code for non-virtual function found? Same way as ordinary functions: Compiler generates function code and assigns address Address of code is placed in symbol table At call site, address is taken from symbol table and placed in compiled code But some special scoping rules for classes Overloading Remember: overloading is resolved at compile time Different from run-time lookup of virtual function slide 20

Scope Rules in C++ Scope qualifiers: ::, ->, and. class::member, ptr->member, object.member A name outside a function or class, not prefixed by :: and not qualified refers to global object, function, enumerator or type A name after X::, ptr-> or obj. refers to a member of class X or a base class of X Assume ptr is pointer to class X and obj is an object of class X slide 21

Virtual vs. Overloaded Functions class parent { public: void printclass() {printf("p ");}; virtual void printvirtual() {printf("p ");}; }; class child : public parent { public: void printclass() {printf("c ");}; virtual void printvirtual() {printf("c ");}; }; main() { parent p; child c; parent *q; p.printclass(); p.printvirtual(); c.printclass(); c.printvirtual(); q = &p; q->printclass(); q->printvirtual(); q = &c; q->printclass(); q->printvirtual(); } Output: p p c c p p p c slide 22

Subtyping Subtyping in principle A <: B if every A object can be used without type error whenever a B object is required Example: Point: ColorPoint: int getx(); void move(int); int getx(); int getcolor(); void move(int); void darken(int tint); Public members Public members C++: A <: B if class A has public base class B slide 23

No Subtyping Without Inheritance class Point { public: int getx(); void move(int); protected:... private:... }; class ColorPoint { public: int getx(); void move(int); int getcolor(); void darken(int); protected:... private:... }; C++ does not treat ColorPoint <: Point (as written) Need public inheritance ColorPoint : public Point slide 24

Why This Design Choice? Client code depends only on public interface In principle, if ColorPoint interface contains Point interface, then any client could use ColorPoint in place of Point Without link to inheritance, subtyping leads to loss of implementation efficiency Also encapsulation issue Subtyping based on inheritance is preserved under modifications to base class slide 25

Function Subtyping Subtyping principle A <: B if an A expression can be safely used in any context where a B expression is required Subtyping for function results If A <: B, then C A <: C B Covariant: A <: B implies F(A) <: F(B) Subtyping for function arguments If A <: B, then B C <: A C Contravariant: A <: B implies F(B) <: F(A) slide 26

Examples If circle <: shape, then circle shape circle circle shape shape shape circle C++ compilers recognize limited forms of function subtyping slide 27

Abstract Classes Abstract class: a class without complete implementation Declared by =0 (what a great syntax! ) Useful because it can have derived classes Since subtyping follows inheritance in C++, use abstract classes to build subtype hierarchies. Establishes layout of virtual function table (vtable) slide 29

Multiple Inheritance Shape ReferenceCounted Rectangle RefCounted Rectangle Inherit independent functionality from independent classes slide 30

Problem: Name Clashes class A { public: void virtual f() { } }; class B { public: void virtual f() { } }; class C : public A, public B { }; C* p; p->f(); // error same name in two base classes slide 31

Solving Name Clashes Three general approaches No solution is always best Implicit resolution Language resolves name conflicts with arbitrary rule Explicit resolution used by C++ Programmer must explicitly resolve name conflicts Disallow name clashes Programs are not allowed to contain name clashes slide 32

Explicit Resolution of Name Clashes Rewrite class C to call A::f explicitly class C : public A, public B { public: void virtual f( ) { A::f( ); // Call A::f(), not B::f(); } Eliminates ambiguity Preserves dependence on A Changes to A::f will change C::f slide 33

vtable for Multiple Inheritance class A { public: int x; virtual void f(); }; class B { public: int y; virtual void g(); virtual void f(); }; class C: public A, public B { public: int z; virtual void f(); }; C *pc = new C; B *pb = pc; A *pa = pc; Three pointers to same object, but different static types. slide 34

Object Layout A B C C object C-as-A vtbl pa, pc pb vptr A data vptr B data C data A object B object & C::f 0 C-as-B vtbl & B::g 0 & C::f δ Offset δ in vtbl is used in call to pb->f Call to pc->g can proceed through C-as-B vtbl slide 35

Multiple Inheritance Diamond Window (D) Text Window (A) Graphics Window (B) Text, Graphics Window (C) Is interface or implementation inherited twice? What if definitions conflict? slide 36

Diamond Inheritance in C++ D Standard base classes D members appear twice in C Virtual base classes class A : public virtual D { } Avoid duplication of base class members Require additional pointers so that D part of A, B parts of object can be shared A C A part B part C part D part B C++ multiple inheritance is complicated in part because of desire to maintain efficient lookup slide 37

C++ Summary Objects Created by classes Contain member data and pointer to class Classes: virtual function table Inheritance Public and private base classes, multiple inheritance Subtyping: occurs with public base classes only Encapsulation Member can be declared public, private, protected Object initialization partly enforced slide 38