Object Oriented Software Design II

Similar documents
C++ classes. Giuseppe Lipari April 27, Scuola Superiore Sant Anna Pisa

Advanced course on C++

Object Oriented Software Design II

Object Oriented Software Design II

Fundamentals of Programming

Informatica e Sistemi in Tempo Reale

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Programming in C and C++

CS201- Introduction to Programming Current Quizzes

Introduction to the C programming language

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Introduction to the C programming language

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

Classes. Christian Schumacher, Info1 D-MAVT 2013

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Pointers, Dynamic Data, and Reference Types

CS201 Some Important Definitions

2 ADT Programming User-defined abstract data types

Lecture 2, September 4

Interview Questions of C++

Fast Introduction to Object Oriented Programming and C++

AN OVERVIEW OF C++ 1

Introduction to the C programming language

EL2310 Scientific Programming

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

Absolute C++ Walter Savitch

COMP 2355 Introduction to Systems Programming

Object-Oriented Principles and Practice / C++

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Evolution of Programming Languages

Object Oriented Programming. Solved MCQs - Part 2

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Where do we go from here?

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Object Oriented Software Design - II

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Dynamic Data Structures

A brief introduction to C++

COMP6771 Advanced C++ Programming

Design Patterns in C++

Financial computing with C++

CS3157: Advanced Programming. Outline

377 Student Guide to C++

7.1 Optional Parameters

Introduction to Programming Using Java (98-388)

Chapter 2. Procedural Programming

Fundamentals of Programming

Pointers. Developed By Ms. K.M.Sanghavi

G52CPP C++ Programming Lecture 13

Problem Solving with C++

Constants, References

Introducing C++ to Java Programmers

Design Patterns in C++

CS304 Object Oriented Programming Final Term

C++ 8. Constructors and Destructors

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

G52CPP C++ Programming Lecture 20

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

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

Intermediate Programming & Design (C++) Classes in C++

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Chapter 17 vector and Free Store. Bjarne Stroustrup

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

C++_ MARKS 40 MIN

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

In Java we have the keyword null, which is the value of an uninitialized reference type

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Object-Oriented Programming, Iouliia Skliarova

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Introduction To C#.NET

Ch. 12: Operator Overloading

OBJECT ORIENTED PROGRAMMING

Object Oriented Software Design

Programming, numerics and optimization

Ch. 10: Name Control

B16 Object Oriented Programming

Smart Pointers. Some slides from Internet

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

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

CSE 303: Concepts and Tools for Software Development

Come and join us at WebLyceum

OOSD. Introduction to JAVA. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. September 12, 2011

Vector and Free Store (Pointers and Memory Allocation)

Pointers and References

Fundamentals of Programming

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

6. Pointers, Structs, and Arrays. 1. Juli 2011


Design Patterns in C++

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS24 Week 3 Lecture 1

Transcription:

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

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 2 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 3 / 54

Prerequisites To understand this course, you should at least know the basic C syntax functions declaration and function call, global and local variables pointers (will do again during the course) structures First part of the course: classes Classes, objects, memory layout Pointer and references Copying Inheritance, multiple inheritance Access rules Public, protected and private inheritance Exceptions G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 4 / 54

Summary - cont. Second part: templates Templates The Standard Template Library Third part: new standard What does it change lambda functions auto move semantic new STL classes Safety to exceptions Fourth part: patterns Some patterns in C++ Function objects Template patterns Meta-programming with templates Fifth part: libraries Thread library, synchronization Futures and promises The Active Object pattern G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 5 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 6 / 54

Classes C is not a high-level language. Brian Kernighan, inventor of C with D. M. Ritchie Those types are not abstract: they are as real as int and float Actually I made up the term object-oriented, and I can tell you I did not have C++ in mind. Doug McIlroy Alan Kay G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 7 / 54

Abstraction An essential instrument for OO programming is the support for data abstraction C++ permits to define new types and their operations Creating a new data type means defining: Which elements it is composed of (internal structure); How it is built/destroyed (constructor/destructor); How we can operate on this type (methods/operations). G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 8 / 54

Data abstraction in C We can do data abstraction in C (and in almost any language) typedef struct complex { double real_; double imaginary_; } cmplx; void add_to(cmplx *a, cmplx *b); void sub_from(cmplx *a, cmplx *b); double get_module(cmplx *a); We have to pass the main data to every function name clashing: if another abstract type defines a function add_to(), the names will clash! No information hiding: any user can access the internal data using them improperly G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 9 / 54

Classical example class Complex { double real_; double imaginary_; public: Complex(); Complex(double a, double b); ~Complex(); }; double real() const; double imaginary() const; double module() const; Complex &operator =(const Complex &a); Complex &operator+=(const Complex &a); Complex &operator-=(const Complex &a)); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 10 / 54

How to use complex Complex c1; Complex c2(1,2); Complex c3(3,4); // default constructor // constructor // constructor cout << "c1=(" << c1.real() << "," << c1.imaginary() << ")" << endl; c1 = c2; // assignment c3 += c1; // operator += c1 = c2 + c3; // ERROR: operator + not yet defined G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 11 / 54

Using new data types The new data type is used just like a predefined data type it is possible to define new functions for that type: real(), imaginary() and module() It is possible to define new operators =, += and -= The compiler knows automatically which function/operator must be invoked C++ is a strongly typed language the compiler knows which function to invoke by looking at the type G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 12 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 13 / 54

Class Class is the main construct for building new types in C++ A class is almost equivalent to a struct with functions inside In the C-style programming, the programmer defines structs, and global functions to act on the structs In C++-style programming, the programmer defines classes with embedded functions class MyClass { int a; public: int myfunction(int param); }; Class declaration Remember the semicolon! G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 14 / 54

Members A class contains members A member can be any kind of variable (member variables) any kind of function (member functions or methods) class MyClass { int a; double b; public: int c; }; void f(); int geta(); int modify(double b); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 15 / 54

Members A class contains members A member can be any kind of variable (member variables) any kind of function (member functions or methods) class MyClass { int a; double b; public: int c; member variables (private) }; void f(); int geta(); int modify(double b); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 15 / 54

Members A class contains members A member can be any kind of variable (member variables) any kind of function (member functions or methods) class MyClass { int a; double b; public: int c; }; void f(); int geta(); int modify(double b); member variables (private) member variable (public) G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 15 / 54

Members A class contains members A member can be any kind of variable (member variables) any kind of function (member functions or methods) class MyClass { int a; double b; public: int c; }; void f(); int geta(); int modify(double b); member variables (private) member variable (public) member functions (public) G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 15 / 54

Declaring objects of a class: constructor An object is an instance of a class An object is created by calling a special function called constructor A constructor is a function that has the same name of the class and no return value It may or may not have parameters; It is invoked in a special way class MyClass { public: MyClass() { cout << "Constructor"<<endl; } }; MyClass obj; Declaration of the constructor Invoke the constructor to create an object G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 16 / 54

Constructor - II Constructors with parameters class MyClass { int a; int b; public: MyClass(int x); MyClass(int x, int y); }; MyClass obj; MyClass obj1(2); MyClass obj2(2,3); int myvar(2); double pi(3.14); A class can have many constructors This is an error, no constructor without parameters Calls the first constructor Calls the second constructor Same syntax is valid for primitive data types G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 17 / 54

Default constructor Rules for constructors If you do not specify a constructor, a default one with no parameters is provided by the compiler If you provide a constructor (any constructor) the compiler will not provide a default one for you Constructors are used to initialise members class MyClass { int a; int b; public: MyClass(int x, int y) { a = x; b = 2*y; } }; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 18 / 54

Initialization list Members can be initialised through a special syntax This syntax is preferable (the compiler can catch some obvious mistake) use it whenever you can (i.e. almost always) class MyClass { int a; int b; public: MyClass(int x, int y) : a(x), b(y) { // other initialisation } }; A comma separated list of constructors, following the : G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 19 / 54

Accessing member objects Members of one object can be accessed using the dot notation, similarly to structs in C class MyClass { public: int a; int f(); void g(int i, int ii); }; MyClass x; MyClass y; Assigning to a member variable of object x x.a = 5; y.a = 7; x.f(); y.g(5, 10); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 20 / 54

Accessing member objects Members of one object can be accessed using the dot notation, similarly to structs in C class MyClass { public: int a; int f(); void g(int i, int ii); }; MyClass x; MyClass y; Assigning to a member variable of object x Assigning to a member variable of object y x.a = 5; y.a = 7; x.f(); y.g(5, 10); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 20 / 54

Accessing member objects Members of one object can be accessed using the dot notation, similarly to structs in C class MyClass { public: int a; int f(); void g(int i, int ii); }; MyClass x; MyClass y; x.a = 5; y.a = 7; x.f(); y.g(5, 10); Assigning to a member variable of object x Assigning to a member variable of object y Calling member function f() of object x G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 20 / 54

Accessing member objects Members of one object can be accessed using the dot notation, similarly to structs in C class MyClass { public: int a; int f(); void g(int i, int ii); }; MyClass x; MyClass y; x.a = 5; y.a = 7; x.f(); y.g(5, 10); Assigning to a member variable of object x Assigning to a member variable of object y Calling member function f() of object x Calling member function g() of object y G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 20 / 54

Implementing member functions You can implement a member function (including constructors) in a separate.cpp file complex.h class Complex { double real_; double img_; public:... double module() const;... }; complex.cpp double Complex::module() { double temp; temp = real_ * real_ + img_ * img_; return temp; } This is preferable most of the times put implementation in include files only if you hope to use in-lining optimisation G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 21 / 54

Accessing internal members double Complex::module() const { double temp; temp = real_ * real_ + img_ * img_; return temp; } G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 22 / 54

Accessing internal members double Complex::module() const { double temp; temp = real_ * real_ + img_ * img_; return temp; } scope resolution The :: operator is called scope resolution operator G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 22 / 54

Accessing internal members double Complex::module() const { double temp; temp = real_ * real_ + img_ * img_; return temp; } scope resolution The :: operator is called scope resolution operator like any other function, we can create local variables G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 22 / 54

Accessing internal members double Complex::module() const { double temp; temp = real_ * real_ + img_ * img_; return temp; } scope resolution access to internal variable The :: operator is called scope resolution operator like any other function, we can create local variables member variables and functions can be accessed without dot or arrow G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 22 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 23 / 54

Access control A member can be: private: only member functions of the same class can access it; other classes or global functions can t protected: only member functions of the same class or of derived classes can access it: other classes or global functions can t public: every function can access it class MyClass { private: int a; public: int c; }; MyClass data; cout << data.a; cout << data.c; // ERROR! // OK G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 24 / 54

Access control Default is private An access control keyword defines access until the next access control keyword class MyClass { int a; double b; public: int c; void f(); int geta(); private: int modify(double b); }; private (default) public private again G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 25 / 54

Access control and scope int xx; class A { int xx; public: void f(); }; global variable member variable void A::f() { xx = 5; ::xx = 3; access local xx access global xx } xx = ::xx + 2; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 26 / 54

Why access control? The technique of declaring private members is also called encapsulation In this way we can precisely define what is interface and what is implementation The public part is the interface to the external world The private part is the implementation of that interface When working in a team, each group take care of a module To ensure that the integration is done correctly and without problems, the programmers agree on interfaces G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 27 / 54

Private Some people think that private is synonym of secret they complain that the private part is visible in the header file private means not accessible from other classes and does not mean secret The compiler needs to know the size of the object, in order to allocate memory to it In an hypothetical C++, if we hide the private part, the compiler cannot know the size of the object G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 28 / 54

Friends class A { friend class B; int y; void f(); public: int g(); }; B is friend of A class B { int x; public: void f(a &a); }; void B::f(A &a) { x = a.y; a.f(); } B can access private members of A G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 29 / 54

Friend functions and operator Even a global function or a single member function can be friend of a class class A { friend B::f(); friend h(); int y; void f(); public: int g(); }; friend member function friend global function It is better to use the friend keyword only when it is really necessary because it breaks the access rules. "Friends, much as in real life, are often more trouble than their worth." Scott Meyers G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 30 / 54

Nested classes It is possible to declare a class inside another class Access control keywords apply class A { class B { int a; public: int b; } B obj; public: void f(); }; Class B is private to class A: it is not part of the interface of A, but only of its implementation. However, A is not allowed to access the private part of B!! (A::f() cannot access B::a). To accomplish this, we have to declare A as friend of B G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 31 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 32 / 54

Memory layout Let us recapitulate the rules for the lifetime and visibility of variables Global variables are defined outside of any function. Their lifetime is the duration of the program: they are created when the program is loaded in memory, and deleted when the program exits Local variables are defined inside functions or inside code blocks (delimited by curly braces { and }). Their lifetime is the execution of the block: they are created before the block starts executing, and destroyed when the block completes execution Global and local variables are in different memory segments, and are managed in different ways G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 33 / 54

Memory segments The main data segments of a program are shown below The BSS segment contains global variables. It is divided into two segments, one for initialised data (i.e. data that is initialised when declared), and non-initialised data. The size of this segment is statically decided when the program is loaded in memory, and can never change during execution HEAP STACK BSS Dynamic memory Local variables Global variables G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 34 / 54

Memory segments The main data segments of a program are shown below The STACK segment contains local variables Its size is dynamic: it can grow or shrink, depending on how many local variables are in the current block HEAP STACK BSS Dynamic memory Local variables Global variables G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 34 / 54

Memory segments The main data segments of a program are shown below The HEAP segment contains dynamic memory that is managed directly by the programmer HEAP STACK BSS Dynamic memory Local variables Global variables G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 34 / 54

Example Here is an example: int a = 5; // initialised global data int b; // non initialised global data int f(int i) // i, d and s[] are local variables { // will be created on the stack when double d; // function f() is invoked char s[] = "Lipari";... } int main() { int s, z; // local variables, are created on the stack // when the program starts } f(); // here f() is invoked, so the stack for f() is created G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 35 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 36 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; Declaration of a pointer to an integer variable *p = 6; p = &b; cout << *p << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; Declaration of a pointer to an integer variable p takes the address of a *p = 6; p = &b; cout << *p << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; *p = 6; Declaration of a pointer to an integer variable p takes the address of a print the address p = &b; cout << *p << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; *p = 6; p = &b; Declaration of a pointer to an integer variable p takes the address of a print the address prints the value in a cout << *p << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; *p = 6; p = &b; Declaration of a pointer to an integer variable p takes the address of a print the address prints the value in a changes the value in a = 6 cout << *p << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; *p = 6; p = &b; cout << *p << endl; Declaration of a pointer to an integer variable p takes the address of a print the address prints the value in a changes the value in a = 6 now p points to b G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Pointer A pointer is a variable that can hold a memory address Basic syntax: int a = 5; int b = 7; int *p; p = &a; cout << p << endl; cout << *p << endl; *p = 6; p = &b; cout << *p << endl; Declaration of a pointer to an integer variable p takes the address of a print the address prints the value in a changes the value in a = 6 now p points to b prints the value in b G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 37 / 54

Arrays The name of an array is equivalent to a constant pointer to the first element With non-const pointers we can do pointer arithmetic char name[] = "Giuseppe"; cout << *name << endl; char *p = name; p++; prints G assert(p == name+1); while (*p!= 0) cout << *(p++); cout << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 38 / 54

Arrays The name of an array is equivalent to a constant pointer to the first element With non-const pointers we can do pointer arithmetic char name[] = "Giuseppe"; cout << *name << endl; char *p = name; p++; assert(p == name+1); prints G declares a pointer to the first element of the array while (*p!= 0) cout << *(p++); cout << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 38 / 54

Arrays The name of an array is equivalent to a constant pointer to the first element With non-const pointers we can do pointer arithmetic char name[] = "Giuseppe"; cout << *name << endl; char *p = name; p++; assert(p == name+1); prints G declares a pointer to the first element of the array Increments the pointer, now points to i while (*p!= 0) cout << *(p++); cout << endl; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 38 / 54

Arrays The name of an array is equivalent to a constant pointer to the first element With non-const pointers we can do pointer arithmetic char name[] = "Giuseppe"; cout << *name << endl; char *p = name; p++; assert(p == name+1); while (*p!= 0) cout << *(p++); cout << endl; prints G declares a pointer to the first element of the array Increments the pointer, now points to i this assertion is correct G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 38 / 54

Arrays The name of an array is equivalent to a constant pointer to the first element With non-const pointers we can do pointer arithmetic char name[] = "Giuseppe"; cout << *name << endl; char *p = name; p++; assert(p == name+1); while (*p!= 0) cout << *(p++); cout << endl; prints G declares a pointer to the first element of the array Increments the pointer, now points to i this assertion is correct zero marks the end of the string G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 38 / 54

Arrays The name of an array is equivalent to a constant pointer to the first element With non-const pointers we can do pointer arithmetic char name[] = "Giuseppe"; cout << *name << endl; char *p = name; p++; assert(p == name+1); while (*p!= 0) cout << *(p++); cout << endl; prints G declares a pointer to the first element of the array Increments the pointer, now points to i this assertion is correct zero marks the end of the string prints the content of address pointed by p, and increments it G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 38 / 54

Dynamic memory Dynamic memory is managed by the user In C: to allocate memory, call function malloc to deallocate, call free Both take pointers to any type, so they are not type-safe In C++ to allocate memory, use operator new to deallocate, use operator delete they are more type-safe G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 39 / 54

The new operator The new and delete operators can be applied to primitive types, and classes operator new automatically calculates the size of memory to be allocated int *p = new int(5); class A {... }; A *q = new A(); Allocates an integer pointed by p delete p; delete q; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 40 / 54

The new operator The new and delete operators can be applied to primitive types, and classes operator new automatically calculates the size of memory to be allocated int *p = new int(5); class A {... }; A *q = new A(); delete p; Allocates an integer pointed by p Does two things: 1) Allocates memory for an object of class A 2) calls the constructor of A() delete q; G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 40 / 54

The new operator The new and delete operators can be applied to primitive types, and classes operator new automatically calculates the size of memory to be allocated int *p = new int(5); class A {... }; A *q = new A(); delete p; delete q; Allocates an integer pointed by p Does two things: 1) Allocates memory for an object of class A 2) calls the constructor of A() Deallocates the memory pointed by p G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 40 / 54

The new operator The new and delete operators can be applied to primitive types, and classes operator new automatically calculates the size of memory to be allocated int *p = new int(5); class A {... }; A *q = new A(); delete p; delete q; Allocates an integer pointed by p Does two things: 1) Allocates memory for an object of class A 2) calls the constructor of A() Deallocates the memory pointed by p Does two things: 1) Calls the destructor for A 2) deallocates the memory pointed by q G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 40 / 54

Destructor The destructor is called just before the object is deallocated. It is always called both for all objects (allocated on the stack, in global memory, or dynamically) If the programmer does not define a constructor, the compiler automatically adds one by default (which does nothing) Syntax class A {... public: A() {... } // constructor ~A() {... } // destructor }; The destructor never takes any parameter G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 41 / 54

Example See./examples/01.summary-examples/destructor.cpp G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 42 / 54

Why a destructor A destructor is useful when an object allocates memory so that it can deallocate it when the object is deleted class A {... }; class B { A *p; public: B() { p = new A(); } ~B() { delete p; } }; p is initialised when the object is created The memory is deallocated when the object is deleted G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 43 / 54

New and delete for arrays To allocate an array, use this form int *p = new int[5]; // allocates an array of 5 int... delete [] p; // notice the delete syntax A *q = new A[10]; // allocates an array of 10... // objects of type A delete [] q; In the second case, the default constructor is called to build the 10 objects Therefore, this can only be done is a default constructor (without arguments) is available G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 44 / 54

Null pointer The address 0 is an invalid address (no data and no function can be located at 0) therefore, in C/C++ a pointer to 0 is said to be a null pointer, which means a pointer that points to nothing. Dereferencing a null pointer is always a bad error (null pointer exception, or segmentation fault) In C, the macro NULL is used to mark 0, or a pointer to 0 however, 0 can be seen to be of integer type, or a null pointer In the new C++, the null pointer is indicated with the constant nullptr this constant cannot be automatically converted to an integer G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 45 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 46 / 54

Function overloading In C++, the argument list is part of the name of the function this mysterious sentence means that two functions with the same name but with different argument list are considered two different functions and not a mistake If you look at the internal name used by the compiler for a function, you will see three parts: the class name the function name the argument list G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 47 / 54

Function overloading class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A_f_int A_f_int_int A_f_double B_f_int To the compiler, they are all different functions! beware of the type... G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 48 / 54

Which one is called? class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A a; B b; a.f(5); b.f(2); a.f(3.0); a.f(2,3); a.f(2.5, 3); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 49 / 54

Which one is called? class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A a; B b; a.f(5); b.f(2); a.f(3.0); a.f(2,3); a.f(2.5, 3); A_f_int G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 49 / 54

Which one is called? class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A a; B b; a.f(5); b.f(2); a.f(3.0); a.f(2,3); a.f(2.5, 3); A_f_int B_f_int G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 49 / 54

Which one is called? class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A a; B b; a.f(5); b.f(2); a.f(3.0); a.f(2,3); a.f(2.5, 3); A_f_int B_f_int A_f_double G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 49 / 54

Which one is called? class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A a; B b; a.f(5); b.f(2); a.f(3.0); a.f(2,3); a.f(2.5, 3); A_f_int B_f_int A_f_double A_f_int_int G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 49 / 54

Which one is called? class A { public: void f(int a); void f(int a, int b); void f(double g); }; class B { public: void f(int a); }; A a; B b; a.f(5); b.f(2); a.f(3.0); a.f(2,3); a.f(2.5, 3); A_f_int B_f_int A_f_double A_f_int_int A_f_int_int G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 49 / 54

Return values Notice that return values are not part of the name the compiler is not able to distinguish two functions that differs only on return values class A { int floor(double a); double floor(double a); }; This causes a compilation error It is not possible to overload a return value G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 50 / 54

Default arguments in functions Sometime, functions have long argument lists Some of these arguments do not change often We would like to set default values for some argument This is a little different from overloading, since it is the same function we are calling! int f(int a, int b = 0); f(12); // it is equivalent to f(12,0); The combination of overloading with default arguments can be confusing it is a good idea to avoid overusing both of them G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 51 / 54

Outline 1 Course contents 2 Introduction to C++ 3 Classes 4 Access Control 5 Memory layout 6 Pointers 7 Function Overloading 8 Exercise G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 52 / 54

Time to do an example Let us implement a Stack of integers class Stack stack;... stack.push(12); stack.push(7);... cout << stack.pop(); cout << stack.pop(); G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 53 / 54

Interface class Stack {... public: Stack(int maxsize); ~Stack(); }; void push(int a); int pop(); int peek(); int size(); Constructor: maxsize is the maximum number of elements on the stack Hint: Use an array to store the elements G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 54 / 54

Interface class Stack {... public: Stack(int maxsize); ~Stack(); }; void push(int a); int pop(); int peek(); int size(); Constructor: maxsize is the maximum number of elements on the stack Destructor Hint: Use an array to store the elements G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 54 / 54

Interface class Stack {... public: Stack(int maxsize); ~Stack(); Constructor: maxsize is the maximum number of elements on the stack }; void push(int a); int pop(); int peek(); int size(); Hint: Use an array to store the elements Destructor Returns the top element G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 54 / 54

Interface class Stack {... public: Stack(int maxsize); ~Stack(); }; void push(int a); int pop(); int peek(); int size(); Constructor: maxsize is the maximum number of elements on the stack Destructor Returns the top element Returns the current number of elements Hint: Use an array to store the elements G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 20, 2012 54 / 54