Object-Oriented Programming

Similar documents
AN OVERVIEW OF C++ 1

CS304 Object Oriented Programming Final Term

An Introduction to C++

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

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

Cpt S 122 Data Structures. Introduction to C++ Part II

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

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Fast Introduction to Object Oriented Programming and C++

Introduction to C++ Introduction to C++ 1

Interview Questions of C++

G52CPP C++ Programming Lecture 13

A brief introduction to C++

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

Introduction to C++ Systems Programming


C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

2 ADT Programming User-defined abstract data types

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

CS

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

CS304 Object Oriented Programming

Programming, numerics and optimization

Introduction Of Classes ( OOPS )

CPSC 427: Object-Oriented Programming

Object Oriented Design

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

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

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

Recharge (int, int, int); //constructor declared void disply();

Programming in C and C++

Data Structures using OOP C++ Lecture 3

Written by John Bell for CS 342, Spring 2018

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

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

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

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

CS201 Latest Solved MCQs

A <Basic> C++ Course

COEN244: Class & function templates

PHY4321 Summary Notes

A <Basic> C++ Course

Object-Oriented Principles and Practice / C++

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

Ch. 12: Operator Overloading

CS201 Some Important Definitions

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

CSC1322 Object-Oriented Programming Concepts

Instantiation of Template class

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

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Ch02. True/False Indicate whether the statement is true or false.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Object-Oriented Programming for Scientific Computing

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

Tokens, Expressions and Control Structures

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Abstraction in Software Development

More class design with C++ Starting Savitch Chap. 11

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

CLASSES AND OBJECTS IN JAVA


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

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

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

Absolute C++ Walter Savitch

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Function Overloading

Object Oriented Programming. Solved MCQs - Part 2

CPSC 427: Object-Oriented Programming

Classes and Objects. Class scope: - private members are only accessible by the class methods.

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

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

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

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

MaanavaN.Com CS1203 OBJECT ORIENTED PROGRAMMING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

C++ for System Developers with Design Pattern

Where do we go from here?

G52CPP C++ Programming Lecture 9

Documentation. Programming / Documentation Slide 42

CSC 210, Exam Two Section February 1999

September 10,

Object-Oriented Programming

VALLIAMMAI ENGINEERING COLLEGE

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

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

C++11 and Compiler Update

PROGRAMMING IN C++ COURSE CONTENT

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV

6.096 Introduction to C++

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

Abstract Data Types (ADT) and C++ Classes

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

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Transcription:

- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56

Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56

I - oriented was initially created by Bjarne Stroustrup and first standardized in 1998. The standard evolves: https://isocpp.org/. The current standard is 17. C programs are valid programs. C makes it easy to shoot yourself in the foot; makes it harder, but when you do it blows your whole leg off. (Bjarne Stroustrup) 3 / 56

II - oriented In addition to the facilities provided by C, provides: additional data types (bool, reference); ; templates; exceptions; namespaces; operator ; function ; free store management operators; additional library facilities. 4 / 56

I/O Library - oriented The I/O operations are defined in the header <iostream>. cin - corresponds to the standard input (stdin). cout - corresponds to the standard output (stdout). The writing operation is achieved using the insertion operator <<. The reading operation is achieved using the extraction operator >>. 5 / 56

References in I - oriented A reference variable or reference is an alias or an alternate name for a variable (for the same memory location). They are particularly useful for function parameter passing by reference (changes inside the functions are reflected after the function finishes). A reference has the same memory address as the original variable. A const reference does not allow the modification of a variable. 6 / 56

References in II - oriented DEMO References are similar to pointers, however there are the following notable differences: A reference must be initialized when it is declared. (On the other hand, pointers can be declared and not initialized or initialized with NULL or nullptr.) Once established to a variable, a reference cannot be changed to reference another variable. (A pointer can be made to point to a different variable than the one it was initialized with). There is no need to use neither dereferencing operator (*), nor the address operator (&) with references. References. (Lecture3 ). 7 / 56

Variable initialization - oriented DEMO Initialize variables using the curly brackets {} ( uniform initialization): int a{2}; The auto specifier specifies that the type of the variable that is being declared will be automatically deduced from its initializer. auto is useful for: avoiding writing long typenames; avoiding repetitions; getting the correct type (and no implicit conversions). References. (Lecture3 ). 8 / 56

Namespaces - oriented DEMO Namespaces provide a method for grouping items together, for preventing name conflicts and for organizing code. A namespace is a declarative region that provides a scope to the identifiers inside it. A namespace can contain functions, variables,. The elements inside a namespace are accesible only by using: the fully qualified name (including the scope resolution operator ::). a using directive. This directive should not be used in header files! Namespaces. (Lecture3 ). 9 / 56

Ranged-based for loop - oriented DEMO Is a more readable equivalent for the for loop, for iterating a container. Ranged-based for loop. (Lecture3 ). 10 / 56

Classes - oriented Figure source: https://devrant.com/rants/77251/c-vs-c 11 / 56

-oriented I - oriented Allows programmers to think in terms of the structure of the problem. The problem is decomposed into a set of objects. s interact with each other to solve the problem. New types of objects are created to model elements from the problem space. The the sense are designed to be closely related to the real world objects. 12 / 56

-oriented II - oriented First, the objects must be identified. s internals (attributes) and behaviour (actions) must be defined. The manner in which the teract must be described (functions). OOP includes and combines the advantages of modularity and reusability. 13 / 56

-oriented III - oriented Primary OOP features Abstraction: separating an object s specification from its implementation. Encapsulation: grouping related data and functions together as objects and defining an interface to those objects. Inheritance: allowing code to be reused between related types. Polymorphism: allowing an object to be one of several types, and determining at runtime how to process it, based on its type. 14 / 56

Real world objects - oriented they all have: a state/characteristics and a behaviour/responsibilities (what they can do). 15 / 56

Software objects - are conceptually similar to real world objects; the state - is stored in fields (data/attributes); the behaviour - is exposed through methods (functions). oriented Figure source: https://docs.oracle.com/javase/tutorial/java/concepts/object.html 16 / 56

Example I - oriented Write a program to simulate how a bacteria population grows inside a human host and how it spreads within a community, over time. The bacterium multiplies with a certain growth rate inside the human body. If the people undergo drug treatment, the bacterium growth is reduced. Because of too many antibiotics, some bacteria mutate and become resistant to treatment. The bacteria can spread by air, whenever two persons meet. According to their level of immunity, some persons might be healed without drugs after a certain interval of time. 17 / 56

Example II - oriented What objects can be identified? What are their characteristics and responsibilities? Bacterium Characteristics: growth rate, antibiotic resistance. Responsibilities: reproduce, mutate. Person Characteristics: bacteria population, immunity level. Responsibilities: undergo treatment, meet other person. 18 / 56

Classes I - oriented Classes enable us to create new types. A class: is a user defined data type; is a template/blueprint from which individual objects are created; specifies what data and what functions will be included in objects of that type. 19 / 56

Classes II - oriented Figure source: http://www.expertphp.in/article/php--and-object 20 / 56

Example - Vector in a plane (2D Vector) - oriented Figure source: http://mathinsight.org/vectors_cartesian_coordinates_2d_3d Characteristics: x and y coordinates/components of the 2D vector (data members). Behaviour (function members/methods): 2D vectors can be added; 2D vectors can be subtracted; 2D vectors can be multiplied by a scalar value; 2D vectors can be rotated; 21 / 56

Class declaration and definition - oriented Figure inspired from: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/ 6-088-introduction-to-c-memory-management-and-c-object-oriented--january-iap-2010/ lecture-notes/mit6_088iap10_lec04.pdf 22 / 56

Class declaration - oriented A class is declared in a header file: it will contain fields and function declarations: class Vector2D { public : double xcoordinate ; double ycoordinate ; public : /* }; */ Rotates the current 2D vector. Input : angle - real value Output : the current 2D vector is rotated with the given angle. void r o t a t e ( double a n g l e ) ; /* Multiplies the current 2D vector with a scalar value. Input : scalarvalue - real number Output : the current 2D vector is multiplied by the given value. */ void m u l t i p l y B y S c a l a r ( double s c a l a r V a l u e ) ; // other methods 23 / 56

Method definition I - oriented In a separate cpp file we define the methods declared in the class. Include the header file containing the class declaration. Use the scope resolution operator :: to indicate that the method is part of the class. #i n c l u d e " Vector2D.h" #i n c l u d e <cmath> void Vector2D : : add ( Vector2D v ) { xcoordinate += v. xcoordinate ; ycoordinate += v. ycoordinate ; } void Vector2D : : r o t a t e ( double a n g l e ) { x C o o r d i n a t e = x C o o r d i n a t e c os ( a n g l e ) y C o o r d i n a t e s i n ( a n g l e ) ; ycoordinate = xcoordinate s i n ( angle ) + ycoordinate cos ( angle ) ; } 24 / 56

Method definition II - oriented Methods can also be defined in the class declaration (header file). These are inline methods. When an inline function is called, the compiler will replace the function call with the actual code from the function. Inlining is best suited to short functions. 25 / 56

Access modifiers I - oriented Access modifiers define where the fields and methods can be accessed from. public fields/methods can be accessed from anywhere. private fields/methods can only be accessed within the class (and from friend functions). protected fields/methods can only be accessed within the class or from child/derived. The default access mode for if private.? Why control access to class members? 26 / 56

Access modifiers II - oriented Member fields should be kept private. The amount of public parts should be minimized. Getters can be used to allow read-only access (from outside the class) to private fields. Setters can be used to modify private fields (from outside the class). double getxcoordinate ( ) { return this >x C oo r d i na t e ; } double getycoordinate ( ) { return this >y C oo r d i na t e ; } Setters can be used to modify private fields (from outside the class). 27 / 56

The this keyword - oriented this - a pointer to the current instance. The this pointer is implicitly passed to every method, to have a reference to the current instance. this is useful if there is a method parameter that has the same name as a class field.? Why use this xcoordinate instead of this.xcoordinate? 28 / 56

The use of const - oriented const can be used to indicate that an object should not be changed; Vector2D ( const Vector2D& v ) ; the const restrictions are verified at compile time; const can be used in a method to indicate that it is not changing the state of the object; in this case, const is part of the function s signature. a non-const method cannot be called for a const object. double getxcoordinate ( ) const { return this >x C oo r d i na t e ; } double getycoordinate ( ) const { return this >y C oo r d i na t e ; } DEMO Const methods. (Lecture3 demo2). 29 / 56

declaration and initialization I - oriented The template/blueprint (data type) for 2D vectors is created objects can be created with this template. An object is an instance of a class, a particular value of the defined type. Different instances can have different sets of values in their fields. 30 / 56

declaration and initialization II - oriented 31 / 56

declaration and initialization III - oriented declaration <class name> <identifier>; DEMO Memory is allocated to store the object (store every attribute value). values should be initialized. Class creation and object initialization. (Lecture3 demo2). 32 / 56

Initialization - Constructors I - oriented A constructor is a special function that is called automatically when an instance of a class is declared; does not return anything; must always have exactly the same name as the class; may have 0 or more parameters; a constructor with no parameters is called a default constructor. is generally public. 33 / 56

Initialization - Constructors II - oriented It is impossible to create an object without a constructor being called. A class must have at least one constructor function (if you don t declare one, an implicit constructor is automatically created). 34 / 56

Default constructors I - oriented A default constructor can be invoked with no arguments; has no arguments or defaults all its arguments. A class should have only one default constructor.? Why? DEMO Default constructors. (Lecture3 demo2). 35 / 56

Default constructors II - oriented When making an array of objects, the default constructor is invoked on each element. The compiler automatically generates a default constructor if none is available. any user defined constructor will prevent the compiler from implicitly declaring a default constructor. 36 / 56

Constructors with parameters - oriented A class can have multiple constructors (constructors can be overloaded), with different number of parameters and/or parameters of different types. Member initialization insert a colon (:) before the constructor s body and then a list of initializations for class members: Vector2D : : Vector2D ( double x, double y ) : xcoordinate{x }, ycoordinate{y} {} 37 / 56

Copy constructors I - oriented Copy constructors are invoked when a copy of the current object is needed: when assigning one class instance to another; when passing object as arguments (pass by value); when returning a value from a function. The input parameter must be a (const) reference to an object of the same type. Vector2D ( const Vector2D& v ) ; 38 / 56

Copy constructors II - oriented Figure source: https://imgur.com/gallery/cfswf 39 / 56

Destructors I - oriented A destructor is a special member function called when the class instance is deallocated: if the instance was dynamically allocated (with new) - the destructor is called when delete is called. if the instance was statically allocated - the destructor is called when it goes out of scope. The destructor must have the same name as the class, prefixed with tilde( ). It does not return anything and does not have any parameters. 40 / 56

Destructors II - oriented DEMO If the class has pointer variables and has some dynamic memory allocations, then one must explicitly create a destructor. Destructors. (Lecture3 demo2). 41 / 56

Allocating and deallocating instances - oriented DEMO new - can be used to allocate a class instance on the heap. delete - must be used for deallocation. Dynamic allocation and deallocation of objects. (Lecture3 demo2). 42 / 56

Constructors and destructors invocation - oriented Constructors are invoked: when a new stack-allocated variable is declared; if we allocate instance using new (on the heap); when a copy of the instance is required (copy constructor): assignment; argument passing by value; return an object from a function (by value). The destructor is invoked: when delete is used to deallocate an instance allocated with new; when an instance allocated on the stack goes out of scope. 43 / 56

I - oriented The built-in operators available in can be overloaded for user-defined types. makes the program easier to write, read and understand. It is just another way of calling a function. Almost all operators can be overloaded; see http://www. tutorialspoint.com/cplusplus/cpp_.htm for the list of overloadable/non-overloadable operators. 44 / 56

II - oriented Definition Use the keyword operator followed by the symbol for the operator being defined. Like any other function definition, it must have parameters and a return type. /* Overloading the + operator to add 2 2D vectors. Input : v - Vector2D Output : a 2D vector representing the sum of the current 2D vector and the parameter v. */ Vector2D operator+(const Vector2D& v ) ; /* Overloading the * operator to multiply a 2D vector with a scalar value. Input : scalarvalue - double Output : a 2D vector representing the product of the current 2D vector and the given scalar value. */ Vector2D operator ( double s c a l a r V a l u e ) ; 45 / 56

III - oriented Using operator Vector2D v3 = v1 + v2 ; // <=> Vector2D v3 = v1. operator +( v2); Vector2D v4 = v1 3 ; // <=> Vector2D v3 = v1. operator *(3) ;? Will the following line work? Why/why not? Vector2D v5 = 3 v1 ; DEMO. (Lecture3 demo3). 46 / 56

Overloading the assignment operator (=) I - oriented The assignment operator is used to copy the values from one object to another already existing object. The compiler will generate an assignment operator, if none was defined. Its default behaviour is memberwise assignment. It makes shallow copies. If the class has pointer variables and has some dynamic memory allocations, then one must explicitly create an assignment operator. 47 / 56

Overloading the assignment operator (=) II - oriented Return value of the assignment operator The return value cannot be void (chain assignment a = b = c would then be impossible). It must return a reference to the object that called the operator function. Vector2D& operator=(const Vector2D& v ) ; Copy constructor vs. assignment operator Vector2D v1{ 1, 1 }; Vector2D v2 {2, 3}; Vector2D v7 = v1 ; // copy constructor is called (a new object is created and data is copied into it) Vector2D v8 ; v8 = v2 ; // assignment operator is called ( the object already exists, data is copied into it) 48 / 56

Rules for operator - oriented Overloaded operators must either be a nonstatic class member function or a global function. The first argument for member-function overloaded operators is always of the class type of the object for which the operator is invoked. Unary operators declared as member functions take no arguments; if declared as global functions, they take one argument. Binary operators declared as member functions take one argument; if declared as global functions, they take two arguments. Overloaded operators cannot have default arguments. Source: https://msdn.microsoft.com/en-us/library/4x88tzx0.aspx 49 / 56

- oriented If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three. (http://en. cppreference.com/w/cpp//rule_of_three) If a class is responsible to manage a resource (heap memory, file, database connection, etc) we need to define: copy constructor; assignment operator; destructor. 50 / 56

Static elements I - oriented Static data members The variables declared as static are characteristic to the class, they do not represent object state. They are global for all objects of the class, shared by all objects. The reference to the variable is performed using the class name and the scope resolution operator (::). DEMO Static elements. (Lecture3 demo3). 51 / 56

Static elements II - oriented Static function members A static function member is characteristic to the class, does not depend on individual objects. It can be called even if no instances of the class exist. A static function can only access other static data members or functions, as well as functions outside the class. The static functions do not have acces to the this pointer. Static functions are accessed using the class name and the scope resolution operator (::). 52 / 56

Friend elements I - oriented Friend functions are used when one wants to allow a function that is not a member of a class to access all private and protected members of the class. The prototype of the function must be placed inside the class, preceded by the keyword friend. class Vector2D { //... public : //... }; // friend function friend void printvectordata ( const Vector2D& v ) ; 53 / 56

Friend elements II - oriented A class can also be a friend of another class: the entire class and all its members are friend of the initial class. class Vector2D { //... public : //... }; // friend class friend class Graphics ; class G r a p h i c s { //... }; DEMO Friend elements. (Lecture3 demo3). 54 / 56

Summary I - oriented Decomposing the problem in a set of objects having characteristics and responsibilities and that interact. OOP features: abstraction, encapsulation, inheritance, polymorphism. objects Class - template, object - instance. The class interface is exposed (header file), the class implementation is hidden (.cpp file). 55 / 56

Summary II - oriented A class has fields (data, attributes) and methods. s are initialized via constructors (default, with parameters, copy constructors). s are destoyed via destructors. allows operator. : If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three. 56 / 56