Presentation is loading. Please wait.

Presentation is loading. Please wait.

METU Computer Engineering Dept.

Similar presentations


Presentation on theme: "METU Computer Engineering Dept."— Presentation transcript:

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

2 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)

3 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; }

4 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; }

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

6 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

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

8 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; };

9 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)

10 C++ Class Definitions Same example, a better version

11 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)

12 Creating and Using Objects

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

14 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

15 Interface and Implementation

16

17 Pointers

18 Examples Three-valued Logic Rational Number

19 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; };

20 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

21 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; }

22 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&); };

23 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);

24 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()];

25 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)

26 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;

27 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

28 Destructor, Copy Constructor, operator=: Default Implementaions

29 Destructor, Copy Constructor, operator=

30 Destructor, Copy Constructor, operator=

31 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

32 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;

33 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

34 Function Templates

35 Function Templates

36 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; };

37 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;

38 Class Templates

39 Class Templates

40 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; } };

41 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; }

42 int main( ) { vector<Employee> v( 3 ); v[0].setValue( "George Bush", ); v[1].setValue( "Bill Gates", ); v[2].setValue( "Dr. Phil", ); 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; }

43 Function Objects

44 Matrices

45 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

46 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;

47 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): ” ;


Download ppt "METU Computer Engineering Dept."

Similar presentations


Ads by Google