The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C

Size: px
Start display at page:

Download "The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C"

Transcription

1 The Four Polymorphisms in C++ When people talk about polymorphism in C++ they usually mean the thing of using a derived class through the base class pointer or reference, which is called subtype polymorphism. But they often forget that there are all kinds of other polymorphisms in C++, such as parametric polymorphism, adhoc polymorphismand coercion polymorphism. These polymorphisms also go by different names in C++, Subtype polymorphism is also known as runtime polymorphism. Parametric polymorphism is also known as compile-time polymorphism. Ad-hoc polymorphism is also known as overloading. Coercion is also known as (implicit or explicit) casting. In this article I'll illustrate all the polymorphisms through examples in C++ language and also give insight on why they have various other names. Subtype Polymorphism (Runtime Polymorphism) Subtype polymorphism is what everyone understands when they say "polymorphism" in C++. It's the ability to use derived classes through base class pointers and references. Here is an example. Suppose you have various cats like these felines, Page 1

2 Polymorphic cats on a mat by James Halliday. Since they are all of Felidae biological family, and they all should be able to meow, they can be represented as classes inheriting from Felid base class and overriding the meow pure virtual function, // file cats.h class Felid { public: virtual void meow() = 0; }; class Cat : public Felid { public: void meow() { std::cout << "Meowing like a regular cat! meow!\n"; } }; class Tiger : public Felid { public: void meow() { std::cout << "Meowing like a tiger! MREOWWW!\n"; } }; Page 2

3 class Ocelot : public Felid { public: void meow() { std::cout << "Meowing like an ocelot! mews!\n"; } }; Now the main program can use Cat, Tiger and Ocelot interchangeably through Felid (base class) pointer, #include <iostream> #include "cats.h" void do_meowing(felid *cat) { } cat->meow(); int main() { Cat cat; Tiger tiger; Ocelot ocelot; do_meowing(&cat); do_meowing(&tiger); do_meowing(&ocelot); } Here the main program passes pointers to cat, tiger and ocelot to do_meowing function that expects a pointer to Felid. Since they are all Felids, the program calls the right meow function for each felid and the output is: Meowing like a regular cat! meow! Meowing like a tiger! MREOWWW! Meowing like an ocelot! mews! Subtype polymorphism is also called runtime polymorphism for a good reason. The resolution of polymorphic function calls happens at runtime through an indirection via the virtual table. Another way of explaining this is that compiler does not locate the address of the function to be called at compile-time, Page 3

4 instead when the program is run, the function is called by dereferencing the right pointer in the virtual table. In type theory it's also known as inclusion polymorphism. Parametric Polymorphism (Compile-Time Polymorphism) Parametric polymorphism provides a means to execute the same code for any type. In C++ parametric polymorphism is implemented via templates. One of the simplest examples is a generic max function that finds maximum of two of its arguments, #include <iostream> #include <string> template <class T> T max(t a, T b) { return a > b? a : b; } int main() { std::cout << ::max(9, 5) << std::endl; // 9 } std::string foo("foo"), bar("bar"); std::cout << ::max(foo, bar) << std::endl; // "foo" Here the max function is polymorphic on type T. Note, however, that it doesn't work on pointer types because comparing pointers compares the memory locations and not the contents. To get it working for pointers you'd have to specialize the template for pointer types and that would no longer be parametric polymorphism but would be ad-hoc polymorphism. Since parametric polymorphism happens at compile time, it's also called compile-time polymorphism. Ad-hoc Polymorphism (Overloading) Ad-hoc polymorphism allows functions with the same name act differently for each type. For example, given two ints and the + operator, it adds them together. Given two std::strings it concatenates them together. This is called overloading. Here is a concrete example that implements function add for ints and strings, #include <iostream> #include <string> Page 4

5 int add(int a, int b) { } return a + b; std::string add(const char *a, const char *b) { std::string result(a); result += b; return result; } int main() { std::cout << add(5, 9) << std::endl; std::cout << add("hello ", "world") << std::endl; } Ad-hoc polymorphism also appears in C++ if you specialize templates. Returning to the previous example about max function, here is how you'd write a max for two char *, template <> const char *max(const char *a, const char *b) { return strcmp(a, b) > 0? a : b; } Now you can call ::max("foo", "bar") to find maximum of strings "foo" and "bar". Coercion Polymorphism (Casting) Coercion happens when an object or a primitive is cast into another object type or primitive type. For example, float b = 6; // int gets promoted (cast) to float implicitly int a = 9.99 // float gets demoted to int implicitly Explicit casting happens when you use C's type-casting expressions, such as (unsigned int *) or(int) or C++'s static_cast, const_cast, reinterpret_cast, or dynamic_cast. Coercion also happens if the constructor of a class isn't explicit, for example, Page 5

6 #include <iostream> class A { int foo; public: A(int ffoo) : foo(ffoo) {} void giggidy() { std::cout << foo << std::endl; } }; void moo(a a) { } a.giggidy(); int main() { } moo(55); // prints 55 If you made the constructor of A explicit, that would no longer be possible. It's always a good idea to make your constructors explicit to avoid accidental conversions. Also if a class defines conversion operator for type T, then it can be used anywhere where type T is expected. For example, class CrazyInt { int v; public: CrazyInt(int i) : v(i) {} operator int() const { return v; } // conversion from CrazyInt to int }; The CrazyInt defines a conversion operator to type int. Now if we had a function, let's say,print_int that took int as an argument, we could also pass it an object of type CrazyInt, #include <iostream> void print_int(int a) { } std::cout << a << std::endl; Page 6

7 int main() { CrazyInt b = 55; print_int(999); // prints 999 print_int(b); // prints 55 } Subtype polymorphism that I discussed earlier is actually also coercion polymorphism because the derived class gets converted into base class type. Page 7

8 Introduction Inheritance, encapsulation and polymorphism are undoubtedly the cornerstones of OOP/OOD in general and C++ in particular. When programming C, it is very easy to remember how things work. You know that when you add an int variable to a structure it mostly grows by four bytes. You know that long is either four or eight bytes long depending on the architecture you re working with. Things are less obvious when moving to C++. OOP brings more abstractions to the program. As a result you are no longer sure if a+b sums two numbers or calls some overloaded operator method that concatenates contents of two files together. In this article, I would like to give you a short insight into what s going on behind the scenes. In particular we ll see how the three whales of OOP work in C++. Things that I am going to show in this article may differ from compiler to compiler. I will talk mostly about g++ (version 4.2.3). Note however, that same ideas apply everywhere. Encapsulation As you know, encapsulation is a principle by which same entity, the object, encapsulates data and methods that manipulate the data. You may be surprised to find out that underneath, class methods are just plain functions. How methods work In C++ there s one fundamental difference between plain functions and class methods. Class methods receive one additional argument and that is the pointer to the object whose data the method is expected to manipulate. I.e. first argument to a method is pointer to this. To speed things up, C++ developers used single CPU register (ECX/RCX on x86/x86_64) to pass pointer to this, instead of passing it via stack as if it was a regular function argument (no longer true in x86_64). Otherwise, objects know nothing about methods that operate on them. Page 8

9 How overloading works Another thing that we have to take care of in C++ is how to distinguish betweensome_function() and some_class::some_function(). Or betweensome_class::some_function( int ) and some_class::some_function() I.e. what s the difference between two methods with the same name that receive different number and type of arguments? What is the difference between method and function that has same name? Obviously, out of linker, compiler and preprocessor, linker is the one that should be aware of the above difference. This is because we may have some_function() in some distant object file. Linker is the component that should find this distant function and interconnect the call to the function and the actual function. Linker uses function name as a unique identifier of the function. To make things work, g++ and any other modern compiler, mangles the name of the method/function and makes sure that: 1. Mangled method name includes name of the class it belongs to (if it belongs to any class). 2. Mangled method name includes number and type of arguments method receives. 3. Mangled method name includes namespace it belongs to. With these three, some_class::some_function() and some_function() will have totally different mangled name. See the following code sample. 01 namespace some_namespace 02 { 03 class some_class 04 { 05 public: 06 some_class() { } 07 void some_method() { } 08 }; Page 9

10 09 }; class some_class 12 { 13 public: 14 some_class() { } 15 void some_method() { } 16 }; void some_method() 19 { 20 int a; 21 } g++ will turn: void some_class::some_method() into _ZN10some_class11some_methodEv void some_namespace::some_class::some_method() into_zn14some_namespace10some_class 11some_methodEv void some_method() into _Z11some_methodv Adding integer argument to void some_method() will turn it from _Z11some_methodv to_z11some_methodi. Page 10

11 How mangling solves the problem So when you create two methods with same name, but with different arguments, compiler turns them into two functions with different names. Later, when linker links the code together it doesn t know that these are two methods of the same class. From linkers standpoint, these are two different functions. Structure and size of the object You probably already know that C++ class and good old C structures are nearly the same thing. Perhaps the only difference is that all class members are private unless specified otherwise. On the contrary, all structure members are public. When looking at the memory layout of the object, it is very similar to C structure. Differences begin when you add virtual methods. Once you add virtual methods to the class, compiler will create virtual methods table for the class. Then it will place pointer to the table in the beginning of each instance of this class. Page 11

12 So, bear in mind that once your class has virtual methods, each object of this class will be four or eight bytes (depends on whether you have 64-bit support or not) bigger. Actually, pointer to the virtual methods table does not have to be at the beginning of the object. It is just handy to keep it at the beginning, so g++ and most of the modern compilers do it this way. Adding virtual methods to the class will also increase amount of RAM your program consumes and its size on your hard drive. How inheritance and polymorphism work Let s say we have two classes. A and B. Class B inherits from class A. 01 #include <iostream> using namespace std; class A 06 { 07 public: 08 A() { a_member = 0; } 09 int a_member; 10 }; Page 12

13 11 12 class B : public A 13 { 14 public: 15 B() : A() { b_member = 0; }; 16 int b_member; 17 }; int main() 20 { 21 A *a = new B; 22 a->a_member = 10; return 0; 25 } The interesting thing to notice here is that a actually points to instance of class B. When dereferencing a_member, we re actually dereferencing a_member that defined in class A, but belongs to class B (via inheritance). To make this happen, compiler has to make sure that common part of both classes (a_member in our case) located at the same offset in the object. Page 13

14 Now what if we have some virtual methods. How basic polymorphism works Let s change our example a bit and add some virtual methods. 01 #include <iostream> using namespace std; class A 06 { 07 public: 08 A() { a_member = 0; } 09 virtual int reset() { a_member = 0; } 10 void set_a_member( int a ) { a_member = a; } 11 int get_a_member() { return a_member; } Page 14

15 12 protected: 13 int a_member; 14 }; class B : public A 17 { 18 public: 19 B() : A() { b_member = 0; }; 20 virtual int reset() { a_member = b_member = 0; } 21 virtual void some_virtual_method() { } 22 void set_b_member(int b ) { b_member = b; } 23 int get_b_member() { return b_member; } 24 protected: 25 int b_member; 26 }; int main() Page 15

16 29 { 30 B *b = new B; 31 A *a = b; b->set_b_member( 20 ); 34 b->set_a_member( 10 ); a->reset(); cout << b->get_a_member() << " " << b->get_b_member() << 39 endl; return 0; 42 } If you compile and run this program it will obviously print 0 0. But how, you may ask. After all we did a->reset(). Without our understanding of polymorphism we could think that we re calling method that belongs to class A. The reason it works is because when compiler sees code that dereferences pointer to A it expects certain internal object structure and when it dereferences pointer to B it expects different object structure. Let us take a look at both of them. Page 16

17 However even more important here is the structure of the virtual methods tables of both classes. It is because of the virtual methods table structure compilers knows what virtual method to call. When it generates the code that dereferences pointer to A, it expects that first method in the virtual methods table of the object will be pointer to right reset() routine. It doesn t really care if the pointer actually points to B object. It will call first method of the virtual methods table anyway. How multiple inheritance works Multiple inheritance makes things much more complicated. The problem is that when class C inherits from both A and B, we should have both members of class A and class B in the instance of class C. 01 #include <iostream> using namespace std; class A Page 17

18 06 { 07 public: 08 A() { a_member = 0; } 09 protected: 10 int a_member; 11 }; class B 14 { 15 public: 16 B() { b_member = 0; } 17 protected: 18 int b_member; 19 }; class C : public A, public B 22 { Page 18

19 23 public: 24 C() : A(), B() { c_member = 0; } 25 protected: 26 int c_member; 27 }; int main() 30 { 31 C c; A *a1 = &c; 34 B *b1 = &c; A *a2 = reinterpret_cast<a *>( &c ); 37 B *b2 = reinterpret_cast<b *>( &c ); printf( "%p %p %p\n", &c, a1, b1 ); Page 19

20 40 printf( "%p %p %p\n", &c, a2, b2 ); return 0; 43 } Once we cast pointer to class C into class B, we cannot keep the value of the pointer as is because first fields in the object occupied by fields defined in class A (a_member). Therefore, when we do casting we have to do a very special kind of casting the one that changes the actual value of the pointer. If you compile and run above code snippet, you will see that all the values are the same except for b1, which should be 4 bytes bigger than other values. Page 20

21 This is what (C style casting in our case) casting does it increments the value of the pointer to make sure that it points to the beginning of the, inherited from B, part of the object. In case you wonder what other types of casting will do, here is a short description. Difference between different casting types There are five types of casting in C reinterpret_cast<>() 2. static_cast<>() 3. dynamic_cast<>() 4. const_cast<>() 5. C style cast. I guess you know already what const_cast<>() does. Also, it is only a compile time casting. C style cast is same as static_cast<>(). This leaves us with three types of casting. 1. reinterpret_cast<>() 2. static_cast<>() 3. dynamic_cast<>() From the above example we learn that reinterpret_cast<>() does nothing to the pointer value and leaves it as is. static_cast<>() and dynamic_cast<>() both modify value of the pointer. The difference between two is that the later relies on RTTI to see if the casting is legal it looks inside the object to see if it truly belongs to the type we re trying to cast from. static_cast<>() on the other hand, simply increments the value of the pointer. Page 21

22 Polymorphism and multiple inheritance Things getting even more complicated when we have virtual methods in each one of the classes A, B and C that we already met. Let s add following virtual methods to the classes. virtual void set_a( int new_a ) { a_member = new_a; } To class A. virtual void set_b( int new_b ) { b_member = new_b; } To class B and virtual void set_c( int new_c ) { c_member = new_c; } To class C. Page 22

23 You could have assumed that even in this case class C objects will have only one virtual tables methods, but this is not true. When you static_cast class C object into class B object, class B object must have its own virtual tables method. If we want to use same casting method as with regular objects (that is adding few bytes to the pointer to reach right portion of the object), then we have no choice but to place another virtual tables method in the middle of the object. As a result, you can have many different virtual methods tables for the same class. The above diagram shows very simple case of inheritance and the truth is that it does not get more complicated than this. Take a look at the following, more complex, class hierarchy. It may surprise you, but structure of the class X object will be quiet simple. In our previous example inheritance hierarchy had two branches. This one has three: 1. A-C-F-X 2. D-G-X 3. B-E-H-X All end up with X of course. They are a little longer than in our previous example, but there is nothing special about them. The structure of the object will be the following: Page 23

24 As a rule of thumb, g++ (and friends) calculates the branches that lead to the target class, class X in our case. Next it creates a virtual methods table for each branch and places all virtual methods from all classes in the branch into virtual methods table. This includes pointer to virtual methods of the class itself. If we project this rule onto our last example. A-C-F-X branch virtual methods table will include pointers to virtual methods from classes A, C, F and X. Same with other two branches. What if we try something even more complicatedback TO TOC The thing is that you can t. Lets say we try to create even more complicated hierarchy by changing class D from our previous example to inherit from class C. Page 24

25 This will immediately create ambiguous inheritance and the compiler will not hesitate to tell you that this is what happened. This is because now class X will have all members of classes A and C twice. Once it will have it via A-C-F-X branch and once via A-C-D-G-X branch. It will not tell you that there s a problem immediately. Instead, once you will try to reference one of the members of X inherited from either A or C, g++ will tell you that it has two variations of the same member/method and that it does not know which one of them to call. This what would be g++ output if you try to compile this file. main.cc: In function 'int main()': main.cc:110: error: request for member 'set_a' is ambiguous main.cc:29: error: candidates are: virtual void A::set_a(int) main.cc:29: error: virtual void A::set_a(int) All this because I was trying to do x.set_a( 20 ); in line 110. Few words about C++ constructors I guess you know what constructors are good for. In light of what we ve seen, you may ask yourself, who is building all those virtual methods tables and who writes right pointer into the object. Page 25

26 Obviously compiler builds all the virtual methods tables. And constructor is the one who fills in the right virtual methods table. And this is another reason why you cannot call constructor directly you don t want to mess up with virtual methods tables. Page 26

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

Short Notes of CS201

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

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

C++ Casts and Run-Time Type Identification

C++ Casts and Run-Time Type Identification APPENDIX K C++ Casts and Run-Time Type Identification Introduction There are many times when a programmer needs to use type casts to tell the compiler to convert the type of an expression to another type.

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

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

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

More information

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

Vector and Free Store (Pointers and Memory Allocation)

Vector and Free Store (Pointers and Memory Allocation) DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides

More information

Introduction to C++ Systems Programming

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

More information

Chapter 17 vector and Free Store. Bjarne Stroustrup

Chapter 17 vector and Free Store. Bjarne Stroustrup Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

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

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

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

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

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

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015 Inheritance & Polymorphism Object-Oriented Programming 236703 Spring 2015 1 1 Abstractions Reminder A class is an abstraction over objects A class hierarchy is an abstraction over classes Similar parts

More information

Casting in C++ (intermediate level)

Casting in C++ (intermediate level) 1 of 5 10/5/2009 1:14 PM Casting in C++ (intermediate level) Casting isn't usually necessary in student-level C++ code, but understanding why it's needed and the restrictions involved can help widen one's

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Inclusion Polymorphism

Inclusion Polymorphism 06D-1 Inclusion Polymorphism Polymorphic code Polymorphic references Up- and Down- Casting Polymorphism and values Polymorphic Arrays Inclusion Polymorphism in Context 06D-2 Polymorphism Ad hoc Universal

More information

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University (5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Introduction to Programming Using Java (98-388)

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

More information

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. Welcome to Teach Yourself p. viii Acknowledgments p. xv Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. 6 Standard C++: A Programming Language and a Library p. 8

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

Dr. Md. Humayun Kabir CSE Department, BUET

Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Converting a value of a given type into another type is known as type-casting. ti Conversion can be implicit or explicit 2 C++

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using

More information

C-style casts Static and Dynamic Casts reinterpret cast const cast PVM. Casts

C-style casts Static and Dynamic Casts reinterpret cast const cast PVM. Casts PVM Casts Casting Casting: explicit type conversion Upcasting: casting to a supertype E.g. cast from Dog to Animal Downcasting: casting to a subtype E.g. cast from Animal to Dog Upcasts are always safe

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Chapter 17 vector and Free Store

Chapter 17 vector and Free Store Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:

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

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

Documentation. Programming / Documentation Slide 42

Documentation.   Programming / Documentation Slide 42 Documentation http://www.math.upb.de/~robsy/lehre/programmierkurs2008/ Programming / Documentation Slide 42 Memory Management (I) There are several types of memory which a program can access: Stack Every

More information

Strict Inheritance. Object-Oriented Programming Winter

Strict Inheritance. Object-Oriented Programming Winter Strict Inheritance Object-Oriented Programming 236703 Winter 2014-5 1 1 Abstractions Reminder A class is an abstraction over objects A class hierarchy is an abstraction over classes Similar parts of different

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

CSE 333 Lecture 9 - intro to C++

CSE 333 Lecture 9 - intro to C++ CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

Cours de C++ Introduction

Cours de C++ Introduction Cours de C++ Introduction Cécile Braunstein cecile.braunstein@lip6.fr Cours de C++ 1 / 20 Généralité Notes Interros cours 1/3 Contrôle TP 1/3 Mini-projet 1/3 Bonus (Note de Participation) jusqu à 2 points

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

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Advanced C++ Topics. Alexander Warg, 2017

Advanced C++ Topics. Alexander Warg, 2017 www.kernkonzept.com Advanced C++ Topics Alexander Warg, 2017 M I C R O K E R N E L M A D E I N G E R M A N Y Overview WHAT IS BEHIND C++ Language Magics Object Life Time Object Memory Layout INTRODUCTION

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

Where do we stand on inheritance?

Where do we stand on inheritance? In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

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

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

More information

QUIZ. Source:

QUIZ. Source: QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Ch. 4: Data Abstraction The only way to get massive increases in productivity is to leverage off other people s code. That

More information

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns This Advanced C++ Programming training course is a comprehensive course consists of three modules. A preliminary module reviews

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

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

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking

More information

G52CPP C++ Programming Lecture 15

G52CPP C++ Programming Lecture 15 G52CPP C++ Programming Lecture 15 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 IMPORTANT No optional demo lecture at 2pm this week Please instead use the time to do your coursework I

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING Classes and Objects So far you have explored the structure of a simple program that starts execution at main() and enables you to declare local and global variables and constants and branch your execution

More information

Object Oriented Programming with c++ Question Bank

Object Oriented Programming with c++ Question Bank Object Oriented Programming with c++ Question Bank UNIT-1: Introduction to C++ 1. Describe the following characteristics of OOP. i Encapsulation ii Polymorphism, iii Inheritance 2. Discuss function prototyping,

More information

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013 ANSI C Data Analysis in Geophysics Demián D. Gómez November 2013 ANSI C Standards published by the American National Standards Institute (1983-1989). Initially developed by Dennis Ritchie between 1969

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Pointers and Memory 1

Pointers and Memory 1 Pointers and Memory 1 Pointer values Pointer values are memory addresses Think of them as a kind of integer values The first byte of memory is 0, the next 1, and so on A pointer p can hold the address

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Pointers. Reference operator (&) ted = &andy;

Pointers. Reference operator (&)  ted = &andy; Pointers We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This way we did not have to care about the physical location of our data within memory,

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Week 8: Operator overloading

Week 8: Operator overloading Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading

More information

Database Systems on Modern CPU Architectures

Database Systems on Modern CPU Architectures Database Systems on Modern CPU Architectures Introduction to Modern C++ Moritz Sichert Technische Universität München Department of Informatics Chair of Data Science and Engineering Overview Prerequisites:

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

Reference operator (&)

Reference operator (&) Pointers Each cell can be easily located in the memory because it has a unique address and all the memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it

More information

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS93SI Handout 04 Spring 2006 Apr Review Answers CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly

More information

Pointers in C/C++ 1 Memory Addresses 2

Pointers in C/C++ 1 Memory Addresses 2 Pointers in C/C++ Contents 1 Memory Addresses 2 2 Pointers and Indirection 3 2.1 The & and * Operators.............................................. 4 2.2 A Comment on Types - Muy Importante!...................................

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

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure you review all previous exams and make sure you fully understand

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

More information

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

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

More information

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1 Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences

More information

Casting and polymorphism Enumeration

Casting and polymorphism Enumeration Casting and polymorphism Enumeration Shahram Rahatlou http://www.roma1.infn.it/people/rahatlou/programmazione++/ Corso di Programmazione++ Roma, 25 May 2009 1 Polymorphic vector of Person vector

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 Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Section 1 Multiple Choice Questions (40 pts total, 2 pts each): Q1: Employee is a base class and HourlyWorker is a derived class, with

More information

5. Applicative Programming. 1. Juli 2011

5. Applicative Programming. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 41 Outline Recapitulation Computer architecture extended: Registers and caches Header files Global variables

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information