Programming in C/C++ Lecture 3

Save this PDF as:

Size: px
Start display at page:

Download "Programming in C/C++ Lecture 3"


1 Prgramming in C/C++ Lecture 3 Natalia Silvis-Cividjian vrije Universiteit amsterdam Object Oriented Prgramming in C++ abut bject riented prgramming (OOP) structures in C classes and bjects in C++ separate cmpilatin Prcedural prgramming the prblem is decmpsed in smaller units named prcedures and data can be assembled in packages, called structures. Data and prcedures are separated. C, Pascal, Frtran, Mdula2 are prcedural languages 1

2 Object riented prgramming Nwadays sftware becmes mre cmplex. Prgrams created in prcedural languages are difficult t manage, hard t maintain and expensive t extend. A new way t prgram : bject riented prgramming (OOP) OOP cmbines data and prcedures in ne single unit = bject. abut OOP Object riented prgramming is a tl fr new challenges in sftware develpment - ffers a clser fit t the way human think - imprves cmmunicatin - imprves the quality f sftware Gal : t design high quality sftware at lw cst Imprtant OOP cncepts: encapsulatin data hiding inheritance plymrphism Objects Essence f OOP: Dn t think abut data and functins separately, think abut bjects. Objects are small bundles f data which knw hw t d thing with themselves. Example: Yu can think: A car is a cllectin f wheels, drs, seats, windws. But think what a car can d: mve, speed up, slw dwn, stp, park, etc. Put everything yu knw abut a car in ne bject. Yu dn t say : the cmputer mves the car. Yu say : the car mves itself. 2

3 Examples f bjects a windw : clse, pen, resize, mve a data structure (list, tree): find, remve srt, insert a file: pen,clse, read,write,rename 3D bject: clr,rtate,resize Classes All cars are bjects f the same type. The descriptin f this type is a class: class Car Advantage: clients f yur class can use it withut wrrying abut hw it wrks. C has structures structure Car string name ; int tpspeed ; int capacity ; ; Car my_car, yur_car; // declare 2 variables f type Car = Frd ; cut << ; structure = class withut actins = Smart" ; yur_car.capacity = 2 ; 3

4 C++ has classes A class is a user-defined type. The variables f this type are bjects. A class can be btained frm a structure if sme member functins are added. Encapsulatin = cmbining a number f items (variables and functins) int a single package such an bject f a class my_ford, yur_mini are OBJECTS f type Vehicle First example with classes #include <istream> using namespace std; class Vehicle public : int weight, capacity; flat tp_speed ; vid printdata() ; ; main() Vehicle my_car ; my_car.printdata(); return 0 ; vid Vehicle::printData() cut << "weight= " << weight << " capacity = " << capacity << " Tp speed= " << tp_speed << endl; Test What is the utput f this prgram? 4

5 Private and public a member (variable r functin) can be private r public a "gd" class keeps its member variables private = data hiding and uses public member functins t access r change each private variable. These public member functins are called accesrs and mutatrs. accesr functin is usually named get***... mutatr functin is usually named set***.. Example: data hiding class Vehicle private: int weight, capacity; flat tpspeed ; public: vid printdata() ; //here are 3 accessr functins int getweight(); int getcapacity(); int gettpspeed(); //and nw the 3 mutatr functins int setweight (int new_weight); int setcapacity (int new_capacity); int settpspeed (flat new_tpspeed); ; Cnstructrs Definitin: A cnstructr is a special member functin autmatically called when an bject is created. Jb: Cnstructrs are used fr bjects initializatin. Rules: the cnstructrs shuld be public a cnstructr must have the same name as the class the cnstructr has n type fr the return value (nt even vid) a class can have mre than 1 cnstructr (verlading) a cnstructr withut arguments is called default cnstructr: Vehicle() if n cnstructr is declared, C++ generates a default cnstructr that des nthing OOP tip: Always include a default cnstructr. 5

6 Destructrs Definitin: A destructr is a special member functin called autmatically when the bject f the class passes ut f scpe (destryed) Jb: a destructr returns memry t the freestre by eliminating all dynamic variables created by the bject. Rules: has the same name as the class but begins with a tilde ~. ~Vehicle () is the destructr f the class Vehicle. has n type fr the value returned, nt even vid. a destructr has n parameters a class can have nly ne destructr OOP tip: always use a destructr if the bject creates dynamic variables Example: cnstructrs & destructrs #include <istream> using namespace std ; class Vehicle private: int weight, capacity; flat tpspeed ; public: vid printdata() ; Vehicle () ; // default cnstructr Vehicle(int new_weight, int new_cap, flat new_tpspeed) ; //anther cnstructr with 3 parameters; ~Vehicle() ; // destructr ; Example: cnstructrs & destructrs vid Vehicle::printdata() cut << "weight= " << weight << " capacity = " << capacity << " tp speed= " << tpspeed << endl ; Vehicle::Vehicle() tpspeed = weight = capacity = 0 ; cut << "Object created " << endl ; Vehicle::Vehicle (int new_weight, int new_cap, flat new_tpspeed) weight = new_weight; capacity = new_cap ; tpspeed = new_tpspeed ; cut << "bject created & initiliazed" << endl ; Vehicle::~Vehicle () cut << "Object destryed"<< endl ; 6

7 Example: cnstructrs & destructrs int main() Vehicle mycar1 ; Vehicle mycar2(10000,4,125) ; mycar1.printdata() ; mycar2.printdata() ; return 0 ; Gives the utput: Object created Object created & initialized weight = 0 capacity = 0 tp speed = 0 weight = capacity = 4 tp speed = 125 Object destryed Object destryed Friend functins Definitin: a friend functin f a class is an rdinary functin which has access t the private members f this class Hw t make a functin friend f a class? list its name in the class definitin by using the keywrd friend Example: friends #include <istream> using namespace std ; cnst int MAX_SIZE = 100; class TemperatureArray private: duble array[max_size]; int size; public: TemperatureArray(); // cnstructr vid add_temperature(duble temperature); bl full() ; friend vid print (cnst TemperatureArray& the_bject); ; 7

8 Example: friends vid print (cnst TemperatureArray& the_bject) fr (int i = 0 ; i < the_bject.size ; i++) cut << the_bject.array[i] << endl ; int main() TemperatureArray my_array ; fr (int i=1 ; i < 10 ; i++) my_array.add_temperature (i) ; print (my_array) ; return 0 ; Example friends TemperatureArray::TemperatureArray() size = 0 ; vid TemperatureArray::add_temperature (duble temperature) if (full() ) cut << "Array is full" << endl ; exit(1) ; else array[size]=temperature ; size = size + 1; bl TemperatureArray::full() return (size==max_size) ; Abstract data types Definitin: a data type is called abstract data type (ADT) if the prgrammer wh uses the type des nt have access t the details f hw the values and functins are implemented Example: C++ predefined types (int, duble, etc) and C++ peratrs. OOP tip: Make sure all the classes yu define are ADT's Hw t make yur class ADT? make all member varibales private separate the specificatin f hw the type is used by a prgrammer (= interface) frm the details f hw the type is implemented (=implementatin) 8

9 Separate cmpilatin A small bject-riented prgram shuld have : an interface file: usually with the extensin xxx.h - a header file that describes the services prvided by the class. an implementatin file: cntains the bdies fr the member functins, usually xxx.cpp an applicatin file, creates and uses bjects f this class, yyy.cpp Rule: Every file using the class must include the apprpriate interface file #include <libclass.h> ; < > fr system interface file, part f standard C++ library #include "myclass.h" ; " " fr immediate interface files, in the same directry as the surce cde Hw t cmpile multiple files? Optin1: Cmpiling by hand: g++ car.cpp wheels.cpp drs.cpp windws.cpp bdy.cpp car.exe Multiple files: gmake Each line in the makefile lks like this: target: which files are necessary [tab] hw t btain the target Optin 2: Use gmake utility gmake reads inf frm a makefile The makefile: car: car. wheels. drs. windws. bdy. g++ car. wheels. drs. windws. bdy. car car.: car.cpp g++ -c Wall car.cpp wheels.: wheels.cpp g++ -c Wall wheels.cpp drs.: drs.cpp g++ -c Wall drs.cpp windws.: windws.cpp g++ -c Wall windws.cpp bdy.: bdy.cpp bdy.h g++ -c Wall bdy.cpp clean: rm f *. 9

10 using #ifndef In rder t avid headers t be included mre than nce, C++ needs sme cnstructin t say : if yu have included this stuff befre, d nt include it again. Use this sequence in the header file: #ifndef STACK_H #define STACK_H...class definitin #endif Example multiple files: stack Prblem: write a class t implement a stack. Use this class in a prgram which reads a wrd as a sequence f letters and types this wrd in reversed rder. Use multiple files and separate cmpilatin. The interface file: stack.h #ifndef STACK_H #define STACK_H struct StackNde char data; StackNde *next ; ; typedef StackNde* StackNdePtr; class Stack private: StackNdePtr tp ; public: Stack() ; ~Stack() ; vid push(char the_symbl); char pp() ; bl empty() ; ; #endif 10

11 Implementatin file: stack.cpp (1/2) #include <istream> #include <cstddef> #include stack.h using namespace std; Stack::Stack() tp = NULL ; Stack::~Stack() char char_crt ; while (!empty()) char_crt = pp() ; //pp calls delete bl Stack::empty() return (tp==null) ; Implementatin file:stack.cpp (2/2) vid Stack::push (char the_symbl) StackNdePtr temp_ptr ; temp_ptr = new StackNde ; temp_ptr->data = the symbl ; temp_ptr->next = tp ; tp = temp_ptr ; char Stack::pp() if (empty ()) cut << Errr: ppping an empty stack.\n"; exit (1) ; char result = tp->data ; StackNdePtr temp_ptr ; temp_ptr = tp ; tp = tp->next ; delete temp_ptr ; return result ; Applicatin prgram: test.cpp #include <istream> #include "stack.h" using namespace std; int main() Stack s ; char next_char, ans ; d cut << "Enter a wrd: "; cin.get (next_char) ; while (next_char!= '\n') s.push(next_char); cin.get(next_char) ; cut << "Written backward is: "; while (!s.empty()) cut << s.pp() ; cut << endl ; cut << "Again?(y/n):" ; cin >> ans ; cin.ignre (10000, '\n'); while (ans!= 'n' && ans!= 'N'); return 0 ; Output: Enter a wrd: bicycle Written backward is: elcycib Again?(y/n): n 11