METU Computer Engineering Dept.

Slides:



Advertisements
Similar presentations
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Advertisements

Class and Objects.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
C++ fundamentals.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
Introduction to C++ Systems Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Case Study - Fractions Timothy Budd Oregon State University.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
1 Chapter 1 C++ Basics Review Reading: Sections 1.4 and 1.5.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
1 Chapter 17 Templates and Exceptions Dale/Weems.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Object-Oriented Programming (OOP) and C++
Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
Chapter 15 - C++ As A "Better C"
Chapter 2 Objects and Classes
C++ Lesson 1.
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Systems Programming.
Chapter 1 C++ Basics Review
Andy Wang Object Oriented Programming in C++ COP 3330
Why exception handling in C++?
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Chapter 2 Objects and Classes
(5 - 1) Object-Oriented Programming (OOP) and C++
Fraction Abstract Data Type
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Variables, Identifiers, Assignments, Input/Output
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
(5 - 1) Object-Oriented Programming (OOP) and C++
Chapter 15 - C++ As A "Better C"
Object-Oriented Programming (OOP) Lecture No. 43
CMSC 341 C++ and OOP.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CMSC 341 C++ and OOP.
Class rational part2.
Department of Computer and Information Science, School of Science, IUPUI Exception Handling Dale Roberts, Lecturer Computer Science, IUPUI
CMSC 341 C++ and OOP.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CMSC 341 C++ and OOP.
CMSC 341 C++ and OOP.
Presentation transcript:

METU Computer Engineering Dept. CENG 213 Data Structures Object-based Programming with C++ Fall 2006 Section 1 Instr: Pınar ŞENKUL

Introducing C++ Developed by Bjarne Stroustruop at Bell Labs C language is enhanced with object-oriented programming capabilities. Originally called “C with Classes”. C++ (name comes from the increment operator)

A Simple Example without OOP features #include <iostream> int main() { int integer1; std::cout << “Enter first integer \n”; std::cin >> integer1; int integer2, sum; std::cout<<“Enter second integer\n”; std::cin >> integer2; sum = integer1+integer2; std::cout << “Sum is” << sum << std::endl; return 0; }

A Simple Example without OOP features #include <iostream> // library is enhanced int main() // mandatory return type { int integer1; std::cout << “Enter first integer \n”; // std::out standart output stream object // << stream insertion operator std::cin >> integer1; // std::cinstandart input stream object // >> stream extraction operator int integer2, sum; //variable declarations anywhere in the block std::cout<<“Enter second integer\n”; std::cin >> integer2; sum = integer1+integer2; std::cout << “Sum is” << sum << std::endl; // concatenation return 0; }

About New Features Object-based: classes, encapsulation, objects, operator overloading Object-oriented: inheritance, polymorphism Generic Programming: Templates  Reusability

Object-based Programming A class is a blueprint Object is an item manufactured by using the blueprint. Define a class Create objects from the class. Use the objects in the main program

Object-based Programming Class: information – data members services - member functions

C++ Class Definitions class IntCell { public: IntCell( ) { storedValue = 0; } IntCell( int initialValue ) { storedValue = initialValue; } int read( ) { return storedValue; } void write( int x ) { storedValue = x; } private: int storedValue; };

C++ Class Definitions Encapsulation : Data and functions are encapsulated in classes Information Hiding: Client can only access to the public part. Define data members as private Define member functions as public. Data members should be accessible through member functions. There may be private functions as well (for auxiliary purpose)

C++ Class Definitions Same example, a better version

C++ Class Definitions Explicit: to prevent implicit type casting e.g. Intcell obj; obj = 37 // not allowed if constucter is defined explicit Default parameter: default initial value. If no value is provided, then initial value is used. Initializer list: to initialize the data members directly. For const data members, the initial value should be set in initializer list. Const member function: to denote that the function is an accessor, it does not change the value of any data member. (mutator functions can change the value of data members) (sometimes they are called get/set or read/write functions)

Creating and Using Objects

Creating and Using Objects :: is the scoping operator. (Classname::member) By “using namespace”, we can drop the classname.

Interface and Implementation It is customary to define interface and implementation in separate files. Interface lists classes and their members. It is typically placed in file named .h Default values are defined in interface Implementation includes implementation of the functions. Implementation includes (#include) the interface file. The interface and implementation must match

Interface and Implementation

Pointers

Examples Three-valued Logic Rational Number

Example:Three-valued Logic #ifndef LOGIC_H #define LOGIC_H enum truth3 {FALSE,UNKNOWN,TRUE}; class Logic3 { public: Logic3(truth3 v) { val = v; }; Logic3 () { val = UNKNOWN; }; Logic3(const Logic3& l3) { val = l3.get(); }; truth3 get () const { return val; }; void set (truth3 v) { val = v; }; Logic3& operator= (Logic3 l3) { val = l3.get(); return *this; }; Logic3 operator! () const; Logic3 operator&& (Logic3 l) const; Logic3 operator|| (Logic3 l) const; private: truth3 val; };

Example:Three-valued Logic Logic3 Logic3::operator! (void) const { Logic3 result(UNKNOWN); switch (val) { case FALSE: result.val = TRUE; break; case TRUE: result.val = FALSE; }; return result; Logic3 Logic3::operator&& (Logic3 rhs) const result.val = val < rhs.get() ? val : rhs.get() ; Logic3 Logic3::operator|| (Logic3 rhs) const result.set(val > rhs.get() ? val : rhs.get()) ; #endif

Example:Three-valued Logic #include <iostream> #include "logic3.h" int main() { Logic3 p(TRUE), q(FALSE), r(UNKNOWN); Logic3 s, t(r); truth3 e1; r.set((!p).get()); r = p && (q || t) && !(q && r) || s; e1 = r.get(); q.set(e1); r = t = r; std::cout << r.get() << std::endl; return 0; }

Example – Rational Number class rational { public: rational (int num, int denom); rational (int num); int getNumerator() const; int getDenominator() const; int operator== (rational); int operator< (rational); int operator> (rational); rational operator+ (rational); rational reciprocal(); rational& operator += (rational); private: int num, denom; void normalize (rational&); };

Parameter Passing Parameter passing mechanisms: call by value: the actual argument is copied to the formal parameter. Changes to the copy do not affect the original variable’s value in the caller call by reference: The caller gives the called function the ability to access the data directly and modify the content By pointers By reference variables (e.g. int &count;) call by constant reference: like “call by reference”, but the modification on the content is prohibited Eg. Double avg(const vector<int> &arr, int n, bool &errorflag);

Reference Variable e.g. Int x=5; Int &y=x; // y becomes an alias for x reference variable should be initialized as declaration type it is used for defining an alias for an existing variable/object generally used for Call-by-reference Renaming an object returned by a complex expression e.g., list<T> & whichList = theLists[hash(x,theLists.Size()];

Return Passing Return by value: return a copy of the object/variable Return by reference: return the reference Return by constant reference: return the reference, but the object returned cannot be modified later on. * Return by value is the safest, in return by reference and return by constant reference, one must make sure that the returned reference will exist after the call returns. (the compiler may not give a warning)

Example const string & findMax( const vector<string> & arr ) { int maxIndex = 0; for( int i = 1; i < arr.size( ); i++ ) if( arr[ maxIndex ] < arr[ i ] ) maxIndex = i; return arr[ maxIndex ]; } const string & findMaxWrong( const vector<string> & arr ) string maxValue = arr[ 0 ]; if( maxValue < arr[ i ] ) maxValue = arr[ i ]; return maxValue;

Destructor, Copy Constructor, operator= C++ provides default functions destructor, copy constructor, operator=. When necessary, new implementations can be provided, overriding the defaults. Destructor: it is called whenever an object goes out of scope or “deleted” Copy Constructor: It is called when a new object is constructed or initialized to a copy of the same object. It is called at the time of declaration with initialization (e.g. IntCell B=C; IntCell B(C); ) call-by-value return-by-value operator= : copy assignment operator

Destructor, Copy Constructor, operator=: Default Implementaions

Destructor, Copy Constructor, operator=

Destructor, Copy Constructor, operator=

Destructor, Copy Constructor, operator= IntCell::IntCell( int initialValue ) { storedValue = new int( initialValue ); } IntCell::IntCell( const IntCell & rhs ) storedValue = new int( *rhs.storedValue ); IntCell::~IntCell( ) delete storedValue; class IntCell { public: explicit IntCell( int initialValue = 0 ); IntCell( const IntCell & rhs ); ~IntCell( ); const IntCell & operator=( const IntCell & rhs ); int read( ) const; void write( int x ); private: int *storedValue; }; I

Destructor, Copy Constructor, operator= const IntCell & IntCell::operator=( const IntCell & rhs ) { if( this != &rhs ) *storedValue = *rhs.storedValue; return *this; } int IntCell::read( ) const return *storedValue; void IntCell::write( int x ) *storedValue = x;

Templates Type independent structures Function templates not actual function, but a pattern for function for each new type, new code is generated (code bloat) Class templates generic class definition

Function Templates

Function Templates

Function Templates – Generic Sort Example // *****Generic Selection Sort****** template <class EltType> void sort (EltType* Elts, int size) { EltType e; short i,j,p; for (i=0;i<=size-2;i++) { e = Elts[i]; p=i; for (j=i+1;j<=size-1;j++) if (Elts[j]<e) {e=Elts[j]; p=j; }; Elts[p]=Elts[i]; Elts[i]=e; };

Function Templates – Generic Sort Example typedef struct {int a,b;} intpair; int operator< (intpair p, intpair q) { if (p.a<q.a) return 1; else if (p.a>q.a) return 0; else return (p.b<q.b); } void main () { char C[5]={'d','c','b','a'}; double D[5]={5.0,3.0,8.0,7.0,1.5}; intpair I [3] ={{1,2},{1,3},{0,8}}; sort (C,4); cout << "\n" << C[0] << C[1] << C[2] << C[3]; sort (D,5); cout << "\n" << D[0] << D[1] << D[2] << D[3] << D[4]; sort (I,3); cout << "\n" << I[0].a << I[1].a << I[2].a;

Class Templates

Class Templates

Class Templates – Generic Pair Example template <typename T1,typename T2> class Pair { T1 _co1; T2 _co2; public: Pair(T1 a1, T2 a2): _co1(a1), _co2(a2) {}; T1 proj1(void) { return _co1; } T2 proj2(void) { return _co2; } Pair<T2,T1> reverse(void) { Pair<T2,T1> p (_co2,_co1); return p; } };

Class Templates – Generic Pair Example #include "gpair.h" #include <iostream> using namespace std; Pair<char,int> nice('a',68); Pair<int,char> odd(0,' '); int main (void) { cout << '\n' << nice.proj1() << " " << nice.proj2() ; odd = nice.reverse(); cout << '\n' << odd.proj1() << " " << odd.proj2(); return 0; }

int main( ) { vector<Employee> v( 3 ); v[0].setValue( "George Bush", 400000.00 ); v[1].setValue( "Bill Gates", 2000000000.00 ); v[2].setValue( "Dr. Phil", 13000000.00 ); cout << findMax( v ) << endl; return 0; } class Employee { public: void setValue( const string & n, double s ) { name = n; salary = s; } const string & getName( ) const { return name; } void print( ostream & out ) const { out << name << " (" << salary << ")"; } bool operator< ( const Employee & rhs ) const { return salary < rhs.salary; } // Other general accessors and mutators, not shown private: string name; double salary; }; // Define an output operator for Employee ostream & operator<< ( ostream & out, const Employee & rhs ) rhs.print( out ); return out; }

Function Objects

Matrices

Exception Handling For error processing In the form of try-throw-catch block Enables the programmer to remove the error-handling code from the main-line of the program’s execution

Exception Handling - Example #include <iostream> using namespace std; class DivideByZeroException{ public{ DivideByZeroException():message(“attempted to divide by zero”){ } const char *what() const {return message;} private: const char *message; } double quotient(int numerator, int denominator) { if (denominator ==0) throw DivideByZeroException(); return static_cast<double> (numerator)/denominator;

Exception Handling - Example #include <iostream> int main() { int number1, number2; double result; cout << “Enter two integers (enter end-of-file to end): “; while (cin >> number1 >> number2) { try{ result = quotient (number1,number2); cout << “The quotient is: << result << endl; } catch (DivideByZeroException ex){ cout << “Exception occurred: “ << ex.what() << “\n”; cout << “\n Enter two integers (enter end-of-file to end): ” ;