How C++ Compilers Implement Object Orientation Eric Powders (ejp2127)

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
A little bit on Class-Based OO Languages CS153: Compilers Greg Morrisett.
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
This lecture is a bit of a departure in that we’ll cover how C++’s features are actually implemented. This implementation will look suspiciously similar.
Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Polymorphism, Virtual Methods and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
ECE122 L22: Polymorphism Using Inheritance April 26, 2007 ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Inheritance.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
1 CSE 303 Lecture 24 Inheritance in C++, continued slides created by Marty Stepp
PolymorphismCS-2303, C-Term Polymorphism Hugh C. Lauer Adjunct Professor (Slides include materials from The C Programming Language, 2 nd edition,
C++ fundamentals.
C++ facts From What all is inherited from parent class in C++? Following are the things which a derived class inherits from its.
Hank Childs, University of Oregon June 3 rd, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / /
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Chapter 15 Polymorphism and Virtual Functions. Learning Objectives Virtual Function Basics – Late binding – Implementing virtual functions – When to use.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Inheritance Inheritance – most important and a useful feature of OOPs supported by C++ | Website for Students | VTU -NOTES -Question Papers.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
CS  C++ allows multiple implementation inheritance  Handy for multiple “is-a” situations  Handy for reusing implementation without “is-a”  Leads.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
11/12/2015© Hal Perkins & UW CSEL-1 CSE P 501 – Compilers Code Shape II – Objects & Classes Hal Perkins Winter 2008.
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Object Oriented Software Development
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Polymorphism, Virtual Methods and Interfaces Version 1.1.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Chapter 10 Chapter 10 Implementing Subprograms. Implementing Subprograms  The subprogram call and return operations are together called subprogram linkage.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CPSC 252Inheritance II Page 1 Inheritance & Pointers Consider the following client code: const int MAXCLOCKS = 2; Clock* clockPtr[ MAXCLOCKS ]; clockPtr[0]
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism, Virtual Methods and Abstract Classes
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Programming Language Concepts (CIS 635)
Inheritance, Polymorphism and the Object Memory Model
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Code Shape II – Objects & Classes Hal Perkins Autumn 2011
Inheritance Dr. Bhargavi Goswami Department of Computer Science
Derived Classes in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Code Shape II – Objects & Classes Hal Perkins Summer 2004
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Overview of C++ Polymorphism
Java Programming Language
Code Shape II – Objects & Classes Hal Perkins Autumn 2009
C++ Object Oriented 1.
Presentation transcript:

How C++ Compilers Implement Object Orientation Eric Powders (ejp2127)

Motivation Couple years ago was asked in an interview, “How do Multiple Inheritance & Virtual Inheritance affect how a C++ compiler lays out class data?” 2

My thoughts were… Well, I don’t know… Actually, forget about MI/VI… how does the compiler lay out class data for “regular” inheritance? Actually, forget about inheritance… how does the compiler lay out class data for a simple class? Does it just lay out the data members in order? …Then how do singular inheritance, multiple inheritance, virtual inheritance affect this? 3

Clearly I did not get that job… Later, went back & searched books & internet… couldn’t find answer to this anywhere! Realized I would need to do the research on my own using a compiler & manually hacking into the insides of objects Didn’t have time to do it then; glad I could finally look into this for class project now Used 2 compilers: gcc 4.5.2, MS Vis Std

Topics Basic class layout Inheritance Polymorphism: Virtual functions, vtables, vpointers Multiple Inheritance Virtual Inheritance (briefly) Dynamic casting (briefly) 5

What is a class? Essentially a collection of data and functions branded with a new type, e.g.,: class foo { char a; int b; }; Can now declare objects of type foo foo objects could occupy 5 bytes; might use 8 If declared int then char, 5 bytes Address of object is addr of 1 st data member 6

Inheritance Method of code reuse in which subclasses inherit some data and methods of their parent class. –Control what’s inherited via access rights Subclasses may override base class methods There may be multiple levels of inheritance –Having multiple levels of inheritance is not called multiple inheritance Mult. levels of inh: each successive derived class inherits some of its parent's data and methods –Including “grandparents’” members, etc up the chain 7

Warning: Next 2 slides are most important slides in the presentation (they provide background & motivation for rest of presentation)

Semantics of C++ Inheritance Assume base class B & derived class D We may then write: D foo;// create object of type D B* bPtr = &foo;// base class ptr points at object D* dPtr = &foo;// derived class ptr points at obj When using bPtr, compiler treats object as “type B” object; can only see members declared by B When using dPtr, compiler treats object as “type D” object; can access members declared by both B & D 9

Why use bPtr if it’s so limiting? Can treat object of type B without having to worry about peculiarities of its depth myFunction (vehicle* bPtr) // vehicle is base class {bPtr -> startVehicle();} Can write code that works for B objs; later it will “just work” whenever pass in a derived obj –Even works for derived class created in few years! Won’t require recompilation Requires compiler to lay out classes consistently to ensure can locate members in future classes without recompilation 10

Inheritance: Class Layout B = base class data; D = derived class data bPtr = base class ptr; dPtr = derived class ptr 11

Inheritance: Class Layout For example, B has 2 data members: int, char D declares addit data mem: string If we try to access the string via bPtr, compiler error 12

Implementing polymorphism: Semantics of virtual functions virtual = invoke the func def appropriate for underlying obj, regardless of ptr type accessing obj with If accessing D obj (via bPtr or dPtr), use D’s func def if supplied; else use B’s func def myFunction (vehicle* bPtr) // vehicle is base class {bPtr -> startVehicle();} How can we compile myFunction if porsche.startVehicle() doesn’t exist yet? 13

The vtable For every class with virtual func, compiler creates a vtable (abbrev: vtbl) vtbl holds an entry for every virt func, & addr of code to invoke func def Enables compiler to, at run-time, quickly find addr to invoke given a class name and func name 14

D’s vtbl Assume B defines 3 virt funcs; D overrides v1 & v2 but not v3. D also defines a 4th virt func Compiler generates this when compiling D class: v1addr of D’s v1 v2addr of D’s v2 v3addr of B’s v3 v4addr of D’s v4 I think MS Vis Std stores this in array, while gcc stores in hash 15

The vpointer Every object of a class with a vtbl holds a vpointer (abbrev: vptr), a ptr to class’s vtbl When compiler sees virt func, it finds obj’s vptr & follows to vtbl to locate addr of func to invoke As long as we put vptr in right spot, compiler can generate code now that invokes func that won’t be written for 3 years Compiler generates code that, given base class ptr, accesses obj’s vptr & looks up entries in vtbl 16

Bottom line Of course the object's class and its vtbl don't have to be created for years into the future; as long as the compiler, at that future time, puts the new class object's vptr in a consistent location (which it should) and populates the vtbl consistently (which it should), code that was written and compiled long ago can still find and search the vtbl and dispatch function calls correctly. 17

Where do we store the vptr? Compiler must be able to, at compile time, generate code that finds vptr even though won’t know obj type until run-time Thus vptr must reside inside B subobject More precisely: vptr must reside in “top-most” class that declares a virtual function 18 As long as compiler puts vptr here, will work when create new D class (porsche) in 3 yrs

Semantics of Multiple Inheritance MI: derived class has multiple immediate "parents" (multiple immediate base classes). Example: class D that’s derived from 2 bases, B1 & B2. –D inherits data & methods from both B1 & B2 –Same as with single inheritance: D may override any of B1’s or B2’s methods –Further classes derived from D will inherit data & methods from D, B1, & B2 19

Example: 2 class hierarchies We’ll now create class DD inherited from both D1 & D2 20

Per C++ language rules, different ways to handle DD obj: B1* bPtr1 = new DD; D1* dPtr1 = new DD; B2* bPtr2 = new DD; D2* dPtr2 = new DD; DD* ddPtr = new DD; Compiler must access data & functions properly Compiler must invoke proper version of virtual functions 21

How should the compiler lay out DD's class data?

Quick overview Key: must vet access via all 5 ptrs Access via bPtr1 (B1*) Access via dPtr1 (D1*) Access via bPtr2 (B2*) –requires another vptr Access via dPtr2 (D2*) They point into middle of DD object! –bPtr1 & bPtr2 hold dft addrs tho pt to same obj Access via ddPtr (DD*) 23

Semantics of virtual inheritance What if had this? –base class B1 –2 classes each directly derived from B1: D1 & D2 –Class DD inherited from both D1 & D2 Class DD now has 2 copies of base B1 –2 copies of each data member; can get very messy If use virtual inheritance, class DD only contains 1 copy of base B1 (per semantics of VI) –Opens a whole new can of worms 24

Unfortunately would take too long to provide detailed explanation of how compiler handles VI (if interested, please read my report!)

Data layout: D1, D2, DD, B1 Sole copy of B1 class data moved to end of obj D1 & D2 subobjects have ptr to B1 data Objects now have as many as 3 vptrs dPtr1, dPtr2, bPtr1 all point to dft addrs Explained in detail in my report! 26 Sneak peek…

Due to time constraints, must skip over dynamic casting too… Dynamic casting: instructing compiler to reinterpret a pointer of 1 type as a pointer to another type in the same hierarchy ddPtr = dynamic_cast (bPtr1); Instructs compiler to reinterpret bPtr1 as if it were a ddPtr (of type DD*) Can be very complicated operation with MI/VI because ptrs point to different addrs in same obj! –Can dynamic_cast to type void* to determine the address of the beginning of an object This is covered in my report as well 27

In conclusion… Really glad I did this Feel like I really learned a lot Glad I could compare 2 compilers, & see that they mostly handle object orientation in similar fashion Questions? 28