EL2310 Scientific Programming

Similar documents
EL2310 Scientific Programming

EL2310 Scientific Programming

EL2310 Scientific Programming

EL2310 Scientific Programming

CSE 303: Concepts and Tools for Software Development

Programming, numerics and optimization

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

eingebetteter Systeme

CS11 Introduction to C++ Fall Lecture 1

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

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

CS24 Week 3 Lecture 1

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Absolute C++ Walter Savitch

Interview Questions of C++

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

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

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

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

AN OVERVIEW OF C++ 1

CS

CSI33 Data Structures

PHY4321 Summary Notes

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

CS11 Intro C++ Spring 2018 Lecture 1

CS93SI Handout 04 Spring 2006 Apr Review Answers

Short Notes of CS201

Data Structures using OOP C++ Lecture 3


CS201 - Introduction to Programming Glossary By

COMSW Introduction to Computer Programming in C

Review: C++ Basic Concepts. Dr. Yingwu Zhu

CE221 Programming in C++ Part 1 Introduction

Engineering Tools III: OOP in C++

Lecture 14: more class, C++ streams

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

III. Classes (Chap. 3)

Classes, Constructors, etc., in C++

COMP322 - Introduction to C++

Object-Oriented Programming (OOP) Fundamental Principles of OOP

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

And Even More and More C++ Fundamentals of Computer Science

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

Chapter 10 Introduction to Classes

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Object Oriented Programming in C++

Polymorphism Part 1 1

Midterm Exam 5 April 20, 2015

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

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

CS3157: Advanced Programming. Outline

CSE 333 Lecture smart pointers

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

Fast Introduction to Object Oriented Programming and C++

W3101: Programming Languages C++ Ramana Isukapalli

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Object Oriented Software Design II

CS304 Object Oriented Programming Final Term

Lecture 7. Log into Linux New documents posted to course webpage

G52CPP C++ Programming Lecture 18

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CSE 333 Lecture 9 - intro to C++

PIC 10A Objects/Classes

CS 11 C++ track: lecture 1

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

CS102 C++ Exception Handling & Namespaces

Lecture 18 Tao Wang 1

Inheritance, and Polymorphism.

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

Computer Science II CSci 1200 Lecture 24 C++ Inheritance and Polymorphism

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

A A B U n i v e r s i t y

What does it mean by information hiding? What are the advantages of it? {5 Marks}

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

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

A Tour of the C++ Programming Language

G52CPP C++ Programming Lecture 17

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

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

G52CPP C++ Programming Lecture 20

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Introduction to C++ Systems Programming

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CS304 Object Oriented Programming

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

Introduction to Programming session 24

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

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

Introduction to Object-Oriented Programming

Object Oriented Programming. Solved MCQs - Part 2

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

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

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

CS 162, Lecture 25: Exam II Review. 30 May 2018

Object-Oriented Principles and Practice / C++

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

G52CPP C++ Programming Lecture 9

Transcription:

Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se)

Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Last time Intro to C++ Differences between C and C++ Intro to OOP

Today Object Oriented Programming Classes

Wrap Up Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Wrap Up C++ Compiler Use g++ instead of gcc Usage and command line options are the same as for gcc Make sure you know how to use make for this part of the course!

Wrap Up Declaration of variables You no longer need to declare the variable at the beginning of the function (scope), as was the case for pre C99 Useful rule of thumb: Declare variables close to where they re used. For instance: i only defined within loop for(int i=0;i<n;i++){...} Use specific names for counters, e.g. i,j,k,...

Wrap Up Namespaces In C all function share a common namespace This means that there can only be one function for each function name In C++ can be placed in namespaces Syntax: namespace NamespaceName { void fcn();... } To access a function fcn in namespace A A::fcn To avid typing namespace name in every statement: using namespace std

Wrap Up Printing to Screen In C++ we use streams for input and output Output is handled with the stream cout and cerr In C: printf("the value is %d\n", value); In C++: cout << "The value is " << value << endl; Just like in C you can format the output in a stream You can use cout.width(10) number of characters for output to fill cout.precision(3) number of digits cout.fill( 0 ) pad with a certain character

Wrap Up Getting input from the user Use streams also to get input from console Use the cin stream Ex: int value; cin >> value; If you want to read an entire line, use getline Ex: string line; getline(cin, line); cout << "The input was " << line << endl;

Wrap Up References Constrained and safer pointers Compare int a; int a; int *pa = &a; int &ra = a; int *pa = NULL; - *pa = 10; ra = 10; => a==10 int b; int b; pa = &b; - int *pc; - pc = pa; -

Wrap Up Passing Arguments by Reference in C++ Declaration: void fcn(int &x); Any changed to x inside fcn will affect the parameter used in the function call Ex: void fcn(int &x) { x = 42; } int main() { int x = 1; fcn(x); cout << "x=" << x << endl; } Will change value of x in the scope of main to 42

Wrap Up Dynamic Memory Allocation in C++ In C++ the new and delete operators are used In C we used malloc and free If you allocate an array with new you need to delete with delete [] Ex: int *p = new int[10]; p[0] = 42; delete [] p; Typical mistake, forgotten []

Introduction to Object Oriented Paradigm Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Introduction to Object Oriented Paradigm The Object-Oriented Paradigm The motivation: We are trying to solve complex problems Complex code with many functions and names Difficult to keep track of all details How can we deal with the complexity? Grouping related things Abstracting things away Creating hierarchies of things This also improves: Code re-use Reliability and debugging

Introduction to Object Oriented Paradigm Key Concepts of OOP Classes (types) Instances (objects) Methods Interfaces Access protection - information hiding Encapsulation Composition / aggregation Inheritance Polymorphism

Classes Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Classes Classes A class is an extension of a struct A class can have both data member and function members (methods) Classes bring together data and operations related to that data Like C structs, classes define new data types Unlike structs, they also define how operators work on the new types

Classes Class definition Syntax: class ClassName { public: void fcn(); private: int m X; }; // Do not forget the semicolon!!! m X is a member data void fcn() is a member function public is an access specifier specifying that everything below can be access from outside the class private is an access specifier specifying that everything below is hidden from outside of the class

Classes Access specifiers There are three access specifiers: public private protected No access specifier specified assumes it is private Data and function members that are private cannot be accessed from outside the class Ex: m X above cannot be accessed from outside protected will be discussed later

Classes C++ Structs C++ also uses struct In C++ struct is just like a class (much more than the C struct!) The only difference is the default access protection: class Name { int m X; // Private }; struct Name { int m X; // Public };

Classes Classes and Objects Classes define data types Objects are instances of classes Objects correspond to variables Declaring an object: ClassName variablename;

Classes Classes and Namespace The class defines a namespace Hence function names inside a class do not name clash with other functions Example: the member variable m X above is fully specified as ClassName::m X

Classes Constructor When an object of a certain class is created the so called constructor is called Constructor is a special kind of method. The constructor tells how to setup the objects The constructor that does not take any arguments is called the default constructor The constructor has the same name as the class and has no return type class A { public: A() {} };

Classes Constructor Some types cannot be assigned, only initialized, e.g. references These data members should be initialized in the initializer list of the constructor Try to do as much of the initialization in the initialization in the list rather than using assignment in the body of the constructor Variables are initialized in the order they appear in the list class A { public: A():m X(1) {} private: int m X; };

Classes Constructor class A { public: A():m X(1) {} int getvalue() { return m X; } private: int m X; }; A a; std::cout << a.getvalue() << std::endl;

Classes Constructor You can define several different constructors class MyClass { public: MyClass():m X(1) {} MyClass(int value):m X(value) {} int getvalue() { return m X; } private: int m X; }; MyClass a; // Default constructor MyClass aa(42); // Constructor with argument std::cout << a.getvalue() << std::endl; std::cout << aa.getvalue() << std::endl;

Classes Destructor When an object is deleted the destructor is called The destructor should clean up things For example free up dynamically allocated memory There is only 1 destructor If not declared a default one is used which will not free up dynamic memory Syntax: ClassName(); Class A { public: A(); // Constructor A(); // Destructor... };

Classes Let s look at an example

Classes Task 1 Implement a class the defines a Car Should have a member variable for number of wheels Should have methods to get the number of wheels Write program that instantiate a Car and print number of wheels

Classes Task 2 Write a class Complex for a complex number Provide 3 constructors default - which should create a complex number with value 0 having one argument - should create a real value having two arguments - should create a complex number with real and imaginary part

Classes Source and header file Normally you split the definition from the declaration like in C The definition goes into the header file.h The declaration goes into the source file.cpp Header file ex: class A{ public: A(); private: int m X; }; Source file ex: #include "A.h" A::A():m X(0)

More on Classes and Members Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

More on Classes and Members this pointer Inside class methods you can refer to the object with this pointer The this pointer cannot be assigned (done automatically) Example use in our toy constructor example.

More on Classes and Members const Can have const function arguments Ex: void fcn(const string &s); Pass the string as a reference into the function but commit to not change it For classes this can be used to commit to not change an object as well Ex: void fcn(int arg) const; The function fcn commits to not change anything in the object it belongs to Can only call const functions from a const function or with a const object

More on Classes and Members Static members Members (both functions and data) can be declared static A static member is the same across all objects; it s a member of the class, not any single object That is all instantiated objects share the same static member You can use a static class member without instantiating any object You need to define static data member Ex: (in source file) int A::m Counter = 0; if m Counter is a static data member of class A Static methods can only use static data members! Car example

More on Classes and Members Task 3 Start from the Complex class from last time Add a static int member Every time a new complex number is created the static variable should be incremented Implement the member function Complex& add(const Complex &c); which should add c to the object How does the number of created objects change if we change the function to Complex& add(complex c);

Operator Overloading Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Operator Overloading Operator overloading Operators behave just like functions Compare Complex& add(const Complex &c); Complex& +=(const Complex &c); You can overload (provide your own implementation of) most operators This way you can make them behave in a proper way for your class It will not change the behavior for other classes only the one which overloads the operator Some operators are member functions, some are defined outside class

Operator Overloading Task 4 Use the Complex number class from before. Overload/implement: std::ostream& operator<<(std::ostream &os, const Complex &c); Complex operator+(const Complex &c1, const Complex &c2) Complex operator+(const Complex &c); function) Complex& operator=(const Complex &c); function) (member (member

Operator Overloading Function overloading We can create functions and methods with the same name, but different arguments It is not possible to overload by changing return type Example: void method(); void method(int a); void method(int b, double c); void method(int b); WRONG! int method(int b); WRONG!

Operator Overloading Let s look at operator overloading for the car example. Use case for overloading << Use case for overloading =

Operator Overloading Dynamic allocation of objects One reason to use dynamic memory allocation (new/delete): Moving around pointers to BIG chunks of memory (avoiding unnecessary copying) Makes sense not only for arrays Objects can also be BIG (e.g. database object can be 500MB!) Typically, we dynamically allocate objects We free memory when the object is no longer needed We pass objects by reference (* or &) to functions Example: Database db = new Database("mydatabase.db"); usedb(db); // void usedb(database *db) delete db; db = NULL;

Inheritance Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Inheritance Inheritance Inheritance is a way to show a relation like is a Ex: a car is a vehicle A car inherits many of its properties from being a vehicle These same properties could be inherited by a truck or a bus Syntax: class Car : public Vehicle specifies that Car inherits from Vehicle

Inheritance Inheritance and Constructors If you have three classes A, B and C, where B inherits from A (class B: public A) C inherits from B (class C: public B) When you create C: C c; the constructor from the base classes (B and A) will be run first Execution order 1. Constructor of A 2. Constructor of B 3. Constructor of C

Inheritance Access specifiers private: can be accessed from: inside of the class public: can be accessed from: inside of the class subclasses outside of the class protected: can be accessed from: inside of the class subclasses

Inheritance Class diagrams / UML

Polymorphism and Virtual Functions Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

Polymorphism and Virtual Functions Polymorphism A variable/function can have more than one form Example of polymorphism: operator/function overloading We can have sub-type polymorphism: a variable can be of more than one form A variable of a base type can hold an object of a sub-type In C++ implemented using references or pointers to base classes

Polymorphism and Virtual Functions Polymorphism example class Vehicle {...} class Car: public Vehicle {...} Vehicle *v1 = new Vehicle(); Vehicle *v2 = new Car(); v2 is a Car hidden inside a variable of type pointer to Vehicle! We can then write: v1 = new Car(); So, v1 can hold both a Car and a Vehicle (or even a Truck!) Polymorphism!

Polymorphism and Virtual Functions Subclasses as arguments to function If a function requires as argument a pointer/reference to an object of class A We can provide a pointer/reference to any subclass of A

Polymorphism and Virtual Functions Accessing methods class Vehicle { void drive(); } class Car: public Vehicle { void opentrunk(); } Vehicle *v = new Car(); v->drive(); runs drive() from the Vehicle part of the Car v->opentrunk(); NOT POSSIBLE! But: ((Car *)v)->opentunk(); WORKS!

Polymorphism and Virtual Functions Overloading in sub-classes We can overload a method in a sub-class class Vehicle { void drive(); } class Car: public Vehicle { void drive(); } Vehicle *v1 = new Vehicle(); Vehicle *v2 = new Car(); Car *c = new Car(); v1->drive(); and v2->drive(); run drive() from the Vehicle c->drive(); runs drive() from the Car

Polymorphism and Virtual Functions virtual functions What if we want the object know what it really is and run the correct drive() method? Declare the method with the keyword virtual class Vehicle { virtual void drive(); } class Car: public Vehicle { virtual void drive(); } Vehicle *v1 = new Vehicle(); Vehicle *v2 = new Car(); v1->drive(); runs drive() from the Vehicle v2->drive(); runs drive() from the Car

Polymorphism and Virtual Functions Polymorphism with virtual functions What virtual function to run is determined at run-time Depends on the real type of objects Works for both pointers and references

Polymorphism and Virtual Functions The C project Deadline: Monday 20.10.2014, 20:00 Lab/help session: Friday 10.10.2014, 9-11:00am, Room 22:an, Teknikringen 14

The Standard Template Library (STL) Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes and Members Operator Overloading Inheritance Polymorphism and Virtual Functions The Standard Template Library (STL)

The Standard Template Library (STL) Template Templates offers a way to write code agnostic to data types You write a template for the code Compiler generates a version for each data type you use it with We can write both template classes and functions Example of a template function: template <class T> T getmax (T a, T b) { if(a>b) {return a} else {return b} } getmax<int>(4,5) returns 5 getmax<double>(4.2, 4.1) returns 4.2

The Standard Template Library (STL) Standard Template Library: STL The Standard Template Library (STL) provides classes for: Collections: lists, vectors, sets, maps Defined as templates: can store data of any type! Examples: std::list<t> Ex: std::list<std::string> names; std::vector<t> Ex: std::vector<double> values; std::set<t> Ex: std::set<std::string> nameofperson; std::map<t1,t2> Ex: std::map<int, std::string> nameofmonth; Ex: std::map<std::string, int> monthnumberbyname;

The Standard Template Library (STL) Standard Template Library: STL Different collections are optimized for different use, e.g.: std::list<t> Cannot access elements with x[i], need to use so called iterators to step through the list, can add/remove elements at low cost std::vector<t> Can access elements with x[i], but resizing is more costly std::set<t> Does not allow for redundant elements std::map<t1,t2> Provides a mapping from one object to another More in C++ Library Reference, e.g. http://www.cplusplus.com/reference/stl/list/

The Standard Template Library (STL) Often used: vector (from C++ reference) // erasing from vector #include <iostream> #include <vector> using namespace std; int main () { unsigned int i; vector<unsigned int> myvector; } // set some values (from 1 to 10) for (i=1; i<=10; i++) myvector.push_back(i);

The Standard Template Library (STL) Often used: vector (from C++ reference) // erase the 6th element myvector.erase(myvector.begin()+5); // erase the first 3 elements: myvector.erase(myvector.begin(), myvector.begin()+3); cout << "myvector contains:"; for (i=0; i<myvector.size(); i++) { cout << " " << myvector[i]; cout << endl; } return 0;

The Standard Template Library (STL) Standard Template Library: STL What would be suitable STL structures for: A queue of real time messages? A set of options? Modelling a shipment of products? Differences are important: How to insert an element? How to access/find an element? How to remove an element?

The Standard Template Library (STL) Standard Template Library: STL What would be suitable STL structures for: A queue of real time messages? A set of options? Modelling a shipment of products? Differences are important: How to insert an element? How to access/find an element? How to remove an element?

The Standard Template Library (STL) Presentation 18 on 16. Oct Find out about Expectation-Maximization (EM) algorithm and Monte Carlo Sampling for inference and approximation. Implement examples in C++