Vous êtes sur la page 1sur 187

EJNIKO KAI KAPODISTRIAKO

PANEPISTHMIO AJHNWN
TMHMA PLHROFORIKHS
KAI THLEPIKOINWNIWN

SHMEIWSEIS
ANTIKEIMENOSTRAFOUS
PROGRAMMATISMOU

IZAMPW KARALH
AJHNA 2005
1

Perieqìmeno tou maj matoc


• Genikˆ gia ton antikeimenostraf  programmatismì kai tic
klˆseic
• Dom  kai metagl¸ttish programmˆtwn C++ (me qr sh tou
metaglwttist  g++)
• Diadikastikìc programmatismìc me/se C++
• Embèleia onomˆtwn
• AfaÐresh sta dedomèna (se C++)
• DhmiourgÐa / katastrof  antikeimènwn
• Klhronomikìthta (se C++)
• Polumorfismìc (se C++)
• 'Allec glwssikèc domèc thc C++, krÐsimec gia tic klˆseic
2

B mata katˆ thn Exèlixh tou (AntikeimenostrafoÔc)


ProgrammatismoÔ

Diadikastikìc Programmatismìc (procedural


programming)

• estiˆzei sth sqedÐash twn diadikasi¸n


• “apofˆsise poiec eÐnai oi diadikasÐec pou qreiˆzontai
gia thn ulopoÐhsh kai qrhsimopoÐhse touc kalÔterouc
algorÐjmouc pou mporeÐc na breÐc”
• ParadeÐgmata diadikasi¸n:
– eÔresh thc tetragwnik c rÐzac
– eÔresh M.K.D.
– taxinìmhsh arijm¸n
• Gl¸ssec: Algol60, Algol68, FORTRAN, Pascal, C k.a.

Programmatismìc me StoiqeÐa (modular programming)

• estiˆzei sthn orgˆnwsh twn dedomènwn kai twn


diadikasi¸n
• “apofˆsise poiˆ eÐnai ta stoiqeÐa (modules) pou sou
qreiˆzontai kai q¸rise to prìgrammˆ sou ètsi ¸ste na
krÔyeic dedomèna kai diadikasÐec sta katˆllhla
stoiqeÐa”
• upˆrqoun krit ria gia to qwrismì (bl. [Meyer])
3

• ParadeÐgmata stoiqeÐwn:
– stoiqeÐo diadikasi¸n epexergasÐac proswpikoÔ
– stoiqeÐo diadikasi¸n epexergasÐac eggrˆfwn
– Gl¸ssec: Modula -2, Modula -3 k.a.

AfaÐresh Dedomènwn (data abstraction)

• perissìterh èmfash sta dedomèna


• sundèei tÔpouc me leitourgÐec mèsw twn opoÐwn
qeirizìmaste ta stoiqeÐa touc
• “apofˆsise poioÔc tÔpouc qreiˆzesai, d¸se èna pl rec
sÔnolo leitourgi¸n gia ton kˆje tÔpo”
• ParadeÐgmata tÔpwn: stack (top, pop, push)
• Gl¸ssec: Ada, C++, Java k.a.

Antikeimenostraf c Programmatismìc (Object oriented


programming)

• èkfrash “koin¸n” qarakthristik¸n metaxÔ tÔpwn mèsw


klhronomikìthtac
• “apofˆsise poiec klˆseic jèleic, d¸se èna pl rec
sÔnolo apì leitourgÐec gia thn kˆje klˆsh, èkfrase
rhtˆ tic koinèc leitourgÐec mèsw klhronomikìthtac”
4

• ParadeÐgmata klˆsewn:

"Shape" (color, surface, rotation)


/\
/ \
/ \
"Circle" "Triangle"

• Gl¸ssec: Simula, C++, Java k.a.


5

Gl¸ssec me Qarakthristikˆ AntikeimenostrafoÔc


ProgrammatismoÔ
• ADA
• Smalltalk (1972)
• Modula -3
• C++ (1980)
• Java
• SIMULA (1967): prosfèrei th glwssik  dom  “class” gia
ton orismì klˆsewn, katìpin mporoÔn na oristoÔn
antikeÐmena thc klˆshc, OMWS den upˆrqei mhqanismìc
prostasÐac gia ta onìmata mèsa se mia klˆsh ki ètsi o
qr sthc mporeÐ na prospelˆsei opoiod pote mèroc thc
ulopoÐhshc
6

Upost rixh AntikeimenostrafoÔc ProgrammatismoÔ


• Orismìc klˆsewn, antikeimènwn, klhronomikìthtac
• Dunatìthta elègqou tÔpwn
– leitourgÐec tÔpou mìno pˆnw sta antikeÐmena tou tÔpou
– antikeÐmena tou tÔpou prospelaÔnontai mìno mèsw
leitourgi¸n tou tÔpou
• Dunatìthta upost rixhc egklwbismoÔ (encapsulation)
– epitugqˆnei apìkruyh plhroforÐac (information hiding)
– sundèei ton tÔpo me tic leitourgÐec tou
– mìno ta qarakthristikˆ kai oi leitourgÐec gÐnontai
oratˆ èxw apì thn klˆsh
• Dunatìthta dhmiourgÐac antikeimènwn (stigmiotÔpwn) kai
arqikopoÐhshc touc
• Klhronomikìthta (inheritance)
7

Idiìthtec
• StoiqeiopoÐhsh (“diaÐrei kai basÐleue”)
• Egklwbismìc (apìkruyh plhroforÐac)
• EpanaqrhsimopoÐhsh (reusability)
• Polumorfismìc
– genikeumènoi tÔpoi (stack of(X))
– genikeumènec diadikasÐec (lenghth of list of(X))
– uperfìrtwsh sumbìlwn (Arijmìc + Arijmìc, LÐsta +
LÐsta) (overloading)
8

Genikeumènoi TÔpoi
Parˆdeigma: StoÐbec kai Ourèc
• StoÐbec: apì ta piˆta èwc tic kl seic sunart sewn
• Ourèc: apì touc anjr¸pouc èwc tic diergasÐec

Apìkruyh PlhroforÐac
Parˆdeigma: 'Estw ìti oi genikèc ontìthtec tou probl matoc
eÐnai:
1. “pod lato”
2. “podhlˆthc”
'Estw ìti upˆrqei mia leitourgÐa gia to “pod lato” pou eÐnai
“allag  taqÔthtac” pou pragmatopoieÐtai apì th leitourgÐa
tou “pod latou” “allag  granazioÔ”. Th deÔterh aut 
leitourgÐa thn kratˆme kruf  (thn egklwbÐzoume): den prèpei
na mporeÐ na thn prospelaÔnei ˆmesa o “podhlˆthc”.
9

OnomatologÐa gia tic Klˆseic


Domik  (structural)
DomikoÐ lÐjoi: attributes, data members
Sumperiforˆc (behavioral)
DiadikasÐec mèsw twn opoÐwn prospelaÔnoume ta
antikeÐmena: member functions, procedures,
methods/messages

Klˆseic kai Afhrhmènoi TÔpoi Dedomènwn

• “Object Oriented Design is the construction of software


systems as structured collections of abstract data type
implementations” [Meyer]
• ParadeÐgmata:
– “stack”: ulopoihmèno san sundedemènh lÐsta   array
– “student”: ulopoihmèno mèsw struct   san
sundedemènh lÐsta
• Afhrhmènoi TÔpoi Dedomènwn (ATD) : Afairetik 
perigraf  tÔpwn mèsw twn idiot twn twn leitourgi¸n touc
ki ìqi leptomerei¸n thc anaparˆstas c touc
• Klˆseic : Sugkekrimènh montelopoÐhsh kai ulopoÐhsh
10

C++ Genikˆ
• C++ (=increment of C)
• Sqediˆsthke na
– eÐnai mia kalÔterh C
– uposthrÐzei afaÐresh dedomènwn
– uposthrÐzei antikeimenostraf  programmatismì
• Bjarne Stroustrup, 1980, Bell Labs
• “C me klˆseic”−→ C++ to 1983
• Gia megalÔtera progrˆmmata
• OO qarakthristikˆ empneusmèna apì th Simula67 (C++
=? C + Simula67)
• Embèleia (scope) onomˆtwn-nohmˆtwn
• Klˆseic, antikeÐmena, klhronomikìthta, filikèc klˆseic,
ideatèc klˆseic . . .
11

To Elˆqisto C++ Prìgramma


main()
{
}

Gia na èqoume kai kˆpoia èxodo


#include <iostream.h>

main()
{

cout << "Hello World!" << endl;

H d lwsh #include <iostream.h> dhl¸nei sto


metaglwttist  na perilˆbei tic dhl¸seic pou brÐskontai sto
arqeÐo-epikefalÐda iostream.h
12

Metˆfrash kai ArqeÐa-epikefalÐdec


• Sta arqeÐa-epikefalÐdec (header files) grˆfoume dhl¸seic
(ìqi k¸dika, ektìc an mporeÐ na jewrhjeÐ mèroc miac
d lwshc, oÔte arqikopoi seic   orismoÔc, ektìc an
prìkeitai gia arqikopoi seic stajer¸n)
• #include <iostream.h> : me th qr sh < > anaferìmaste
ston standard include katˆlogo
• #include "my header.h" : anaz thsh tou
arqeÐou-epikefalÐda ston trèqonta katˆlogo
• #include "/home/users/izambo/c++/includes/hed.h" :
dÐdoume ìlo to monopˆti rhtˆ
• g++ -o bla main.cc f.cc
• g++ -c main.cc
• g++ -c f.cc
• g++ -o bla main.o f.o
• Parˆmetroi gia th metagl¸ttish ìpwc perigrˆfontai sto
egqeirÐdio tou g++
-c Compile or assemble the source files, but do not link.
The compiler output is an object file corresponding to
each source file.

..............

-E Stop after the preprocessing stage; do not run the com-


piler proper. The output is preprocessed source code,
which is sent to the standard output.

...............
-o file
Place output in file file.
13

Kˆnte dokimèc metagl¸ttishc qrhsimopoi¸ntac ta parakˆtw


arqeÐa
main.cpp

#include <iostream.h>
#include "p1.h"

main()
{
cout << "hello !"<< endl;
f(5);
}

p1.cpp

#include <iostream.h>

void f(int i)
{
cout << i << endl;
}

p1.h

void f(int);
14

Diadikastikìc Programmatismìc me/se C++


• Dedomèna
– Enswmatwmènoi tÔpoi
– TÔpoi pou orÐzontai apì to qr sth
• DiadikasÐec pˆnw sta dedomèna
– Domikˆ stoiqeÐa thc gl¸ssac kai entolèc
– Sunart seic

Onìmata
• gia tic metablhtèc
• gia tic sunart seic
• gia touc tÔpouc
• ...
• Kˆje ìnoma protoÔ na qrhsimopoihjeÐ prèpei na èqei
dhlwjeÐ. Se èna prìgramma prèpei, gia kˆje ìnoma na
èqoume ènan akrib¸c orismì (ektìc an to ìnoma anafèretai
se ontìthtec diaforetikoÔ eÐdouc, p.q. na
qrhsimopoi soume to Ðdio ìnoma gia ènan tÔpo kai mia
metablht ,   epitrèpetai apì th gl¸ssa rhtˆ, p.q.
uperfìrtwsh onomˆtwn sunart sewn)
15

Dhl¸seic - OrismoÐ - Anajèseic arqik¸n tim¸n

Dhl¸seic (declarations) (POLLES EMFANISEIS)


SÔndesh enìc onìmatoc me ènan tÔpo san perigraf 
extern int error_number;

OrismoÐ (definitions) (MIA EMFANISH) Dèsmeush enìc


onìmatoc me mia sugkekrimènh ontìthta
char ch;

Anˆjesh arqik¸n tim¸n Anˆjesh arqik¸n tim¸n sthn


ontìthta sthn opoÐa anafèretai èna ìnoma
int count = 1;
const double pi = 3.141592;
16

Metablhtèc kai sunart seic: Dhl¸seic - OrismoÐ


• Se mia d lwsh, sundèoume èna ìnoma me to eÐdoc thc
ontìthtac thn opoÐa onomˆzei to ìnoma
• Se ènan orismì dhmiourgoÔme thn ontìthta (desmeÔoume to
q¸ro sth mn mh)
• Mia sunˆrthsh mporeÐ na dhlwjeÐ qwrÐc na oristeÐ dÐnontac
mìno to prìtupì thc
• 'Enac orismìc apoteleÐ tautìqrona kai d lwsh
• H anˆjesh arqik¸n tim¸n se mia metablht  apoteleÐ
tautìqrona kai orismì kai d lws  thc
17

ParadeÐgmata
char ch; <---- DEFINITION

string s; <---- DEFINITION

int count = 1;

const double pi = 3.14159265;

extern int error_number; <---- DECLARATION ONLY !!!!!

const char* Name = "TheName";

const char* season[] =


{"anixi", "kalokeri", "fthinoporo", "ximonas"};

int day(Date* pd) { return pd -> d; } <---- DEFINITION

double sqrt(double); <---- DECLARATION ONLY !!!!!


18

Embèleia (scope)
• Mia d lwsh eisˆgei kˆpoio ìnoma mèsa se mia embèleia
• H embèleia enìc onìmatoc xekinˆ apì th d lwsh tou
onìmatoc
• Metablhtèc:
– kajolikèc (global) (pantoÔ)
– statikèc exwterikèc (èwc to tèloc tou arqeÐou)
– statikèc topikèc se sunˆrthsh (èwc to tèloc thc
ektèleshc thc sunˆrthshc)
– topikèc se sunˆrthsh
– topikèc se block
• Q¸roi onomˆtwn (namespaces)
• Klˆseic k.a.
• Telest c :: (scope resolution operator): gia epÐlush
embèleiac
19

Sunduˆste kajèna apì ta arqeÐa f1.cpp, f2.cpp kai f3.cpp


me to arqeÐo main.cpp, trèxte to ektelèsimo pou prokÔptei
kˆje forˆ kai aitiolog ste ta apotelèsmata thc ektèleshc.
//File: main.cpp
#include <iostream.h>

extern int x;

void f();

main()
{
cout << x << endl;

f();
}

//File: f1.cpp
#include <iostream.h>

int x = 10000;

void f()
{
int x;

x = 1;

cout << x << endl;

{ int x;

x = 2;

cout << x << endl; // prints inner x = 2

}
cout << x << endl; // prints outter x = 1

}
20

// File: f2.cpp
#include <iostream.h>

int x = 20000;

void f()
{
int x = 2;

cout << x << endl; // prints local x

cout << ::x << endl; // prints global x

// File: f3.cpp
#include <iostream.h>

int x = 300000;

void f()
{
int y = x; // assigns global x

int x = 2; // defines a new local x

cout << x << endl ; // prints new x

cout << y <<endl ; // prints y which has the value of global x


}
21

Sunduˆste kajèna apì ta arqeÐa f1.cpp, f2.cpp kai f3.cpp


me to arqeÐo main.cpp, trèxte to ektelèsimo pou prokÔptei
kˆje forˆ kai aitiolog ste ta apotelèsmata thc ektèleshc.

// File: main.cpp
#include <iostream.h>

extern int x;

int f();

main()
{
cout << " x = "
<< x << endl;

cout << "1st output of f() "


<< f() << endl;

cout << "2nd output of f() "


<< f() << endl;

// File: f1.cpp
int x = 10000;

int f()
{
int x = ::x;

return x++;
}
22

// File: f2.cpp
int x = 10000;

int f()
{

static int x = ::x;

return x++;

// File: f3.cpp
static int x = 10000; // CAREFUL: x static to current file!

int f()
{
int x = ::x;

return x++;

}
23

Q¸roi Onomˆtwn (Namespaces)


• 'Ena namespace apoteleÐ mia embèleia
namespace Example{
const double PI = 3.14159;
const double E = 2.71828;
int myInt = 8;
void printValues();
}

• Ena namespace “paketˆrei” dhl¸seic kai sto “pakèto”


dÐnei èna ìnoma
• Mèsa sta namespaces grˆfoume dhl¸seic kai ìqi k¸dika
kai orismoÔc
Apallag  apì th qr sh tou onìmatoc tou q¸rou
onomˆtwn
• Ta onìmata enìc namespace gÐnontai diajèsima èxw apì to
namespace me th qr sh tou using kai plèon den qreiˆzetai
na qrhsimopoihjeÐ to ìnoma tou namespace me qr sh tou
telest  epÐlushc embèleiac (::)
double pp = Example::PI;

using namespace Example;

double ee = E;

• H epÐdrash tou using isqÔei èwc to tèloc thc trèqousac


embèleiac (dhlad , tèloc tou trèqontoc block   tèloc tou
arqeÐou an to using emfanÐzetai èxw apì block)
• Den prèpei na qrhsimopoioÔme using mèsa se
arqeÐa-epikefalÐdec diìti eÐnai polÔ epikÐnduno
24

• To using mporeÐ na anafèretai se olìklhro to namespace


  mìno se kˆpoia apì ta onìmata pou dhl¸nei
• Ta namespaces mporoÔn na epauxˆnontai se ˆlla shmeÐa
tou k¸dika
• Den mporoÔme na epaux soume to namespace me èna nèo
ìnoma apl¸c prosdiorÐzontˆc to me qr sh tou telest 
epÐlushc embèleiac, p.q.
int Example::newInt; // error

Epiplèon dunatìthtec gia touc q¸rouc onomˆtwn


• SÔnjesh kai epilog  apì namespaces
• Alias gia namespaces: dÐnoume qarakthristikˆ onìmata sta
namespaces kai ta metonomˆzoume dÐnontac touc
suntomìtera gia eukolÐa
• An¸numa namespaces: gia th dhmiourgÐa “topik¸n”
“kleist¸n” q¸rwn onomˆtwn
25

Parˆdeigma qr shc namespace


#include <iostream.h>

int myInt = 100000000;

namespace Example{
const double PI = 3.14159;
const double E = 2.71828;
int myInt = 8;
void printValues();
}

main()
{

cout << myInt << endl;

cout << Example::E << endl;

cout << "The namespace myInt: " << Example::myInt << endl ;

Example::printValues();

using namespace Example;

cout << "The namespace E from main: " << E << endl ;

void Example::printValues()
{
cout << "Printing from printValues" << endl;

cout << myInt << endl;

cout << E << endl;

}
26

Parˆdeigma qr shc an¸numou namespace


// Declarations in the unnamed namespace are COMPLETELY hidden
// outside this file. However the names can be used within the file
// as if they are "imported" by a "using" directive
#include <iostream.h>
namespace {
const double PI = 3.14159;
const double E = 2.71828;
int myInt = 8;
void printValues()
{
cout << "Printing from printValues" << endl;

cout << myInt << endl;

cout << E << endl;

}
}

main()
{
cout << myInt << endl;

cout << E << endl;

cout << "The namespace myInt: " << myInt << endl ;

printValues();

}
27

O q¸roc onomˆtwn thc kajierwmènhc biblioj khc


• SÔmfwna me to standard thc C++ [Standard], katargeÐtai
h sÔmbash ta arqeÐa-epikefalÐdec thc standard biblioj khc
na èqoun katˆlhxh .h kai ìla ta onìmata pou orÐzontai  
dhl¸nontai apì aut  brÐskontai mèsa se èna namespace, to
namespace std
• Prokeimènou na gÐnoun ˆmesa prosbˆsima apì to
prìgramma (qwrÐc qr sh tou telest  epÐlushc embèleiac),
prèpei na kˆnoume using to std
• Parˆdeigma
#include <iostream>

main()
{ std::cout << "Printing!\n";}
H alli¸c:
#include <iostream>
using namespace std;

main()
{cout << "Printing!\n";}

• ShmeÐwsh: tìso stic shmei¸seic ìso kai sto mˆjhma qrhsimopoieÐtai tìso h paliˆ

prosèggish gia ta arqeÐa-epikefalÐdec (me thn katˆlhxh .h kai qwrÐc to std) ìso

kai h prosèggish tou standard thc C++.


28

TÔpoi
• TÔpoc boolean (bool) - timèc: true, false -
• TÔpoi qarakt rwn (p.q. char)
• TÔpoi akeraÐwn (p.q. int)
• TÔpoi pragmatik¸n (p.q. double)
• TÔpoi aparÐjmhshc (p.q. enum)
• apousÐa plhroforÐac : void
• TÔpoi deikt¸n (p.q. int* )
• Arrays (p.q. char[])
• TÔpoi anafor¸n (p.q. int& )
• Domèc dedomènwn kai klˆseic

Enswmatwmènoi basikoÐ tÔpoi thc C++


• Gia akeraÐouc diafìrwn megej¸n:
char, short int, int, long int
• Gia pragmatikoÔc:
float, double, long double
• Gia thn ermhneÐa tou pr¸tou bit:
signed/unsigned char
signed/unsigned short int
signed/unsigned int
signed/unsigned long int
29

Ektel¸ntac to akìloujo prìgramma, ja enhmerwjeÐte gia ta


megèjh twn enswmatwmènwn basik¸n tÔpwn ston upologist 
sac
/: C03:Specify.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Demonstrates the use of specifiers
#include <iostream>
using namespace std;

int main() {
char c;
unsigned char cu;
int i;
unsigned int iu;
short int is;
short iis; // Same as short int
unsigned short int isu;
unsigned short iisu;
long int il;
long iil; // Same as long int
unsigned long int ilu;
unsigned long iilu;
float f;
double d;
long double ld;
cout
<< "\n char= " << sizeof(c)
<< "\n unsigned char = " << sizeof(cu)
<< "\n int = " << sizeof(i)
<< "\n unsigned int = " << sizeof(iu)
<< "\n short = " << sizeof(is)
<< "\n unsigned short = " << sizeof(isu)
<< "\n long = " << sizeof(il)
<< "\n unsigned long = " << sizeof(ilu)
<< "\n float = " << sizeof(f)
<< "\n double = " << sizeof(d)
<< "\n long double = " << sizeof(ld)
<< endl;
} ///:~
30

Paragìmenoi TÔpoi
• * dhl¸nei deÐkth (prefix)
• & dhl¸nei anaforˆ (prefix)
• [] dhl¸nei array (postfix)
• () dhl¸nei sunˆrthsh (postfix)
• ParadeÐgmata:
int* a;
float v[10];
char* p[20];
void f(int);

void, deÐktec, arrays


• arijmhtik  se deÐktec ìpwc sth C
• void: suntaktikˆ sumperifèretai san tÔpoc
– na dhl¸sei ìti mia sunˆrthsh den epistrèfei tim 
– basikìc tÔpoc gia deÐktec se antikeÐmena pou den
xèroume ton tÔpo touc
31

'Alla jèmata sqetikˆ me touc tÔpouc


• Metatropèc tÔpwn
• struct
struct address {
char* street;
long number;
char* city;
int postcode;
};

• Gia metonomasÐa tÔpwn, typedef


typedef char* Pchar;
Pchar p1;

Prosoq : H qr sh tou typedef sth C++ eÐnai polÔ


periorismènh. QrhsimopoieÐtai kurÐwc:
– gia onomasÐa paragìmenwn tÔpwn, p.q. char*
– se peript¸seic pou den èqoume akìma apofasÐsei ton
tÔpo kˆpoiwn metablht¸n kai endèqetai na ton
allˆxoume argìtera
• union
• enum (aparijm seic)
• Stouc tÔpouc ja epanèljoume suzht¸ntac gia tic klˆseic
32

EKFRASEIS kai ENTOLES


statement
---------
expression(opt)
declaration
{ statement-list(opt) }
...
33

Telestèc
• p.q. +, -, *, /, %, ...
• EÐnai ploÔsia se telestèc, ìpwc h C
• MerikoÐ èqoun kai nèa shmasÐa, p.q. <<
• Oi telestèc
+, -, *, /, %, &, |, ^, <<, >>
sumptÔssontai me ton =
p.q. a = a + 5; −→ a += 5;
• Genikˆ E1 op= E2 isodÔnamo me E1 = E1 op (E2) (me E1
na upologÐzetai mia forˆ)
• Genikˆ oi telestèc “omadopoioÔntai” apì aristerˆ ektìc
apì touc monadiaÐouc telestèc kai touc telestèc anˆjeshc
pou omadopoioÔntai apì dexiˆ p.q.
a = b = c ----> a = ( b = c )
a + b + c ----> ( a + b ) + c
*p++ ----> * (p++) NOT (*p)++ (Which means what? Guess!)

• Upˆrqei kalˆ orismènh proteraiìthta telest¸n, p.q. oi


telestèc embèleiac, ::, èqoun th megalÔterh kai to kìmma,
, , san èndeixh akoloujÐac èqei th mikrìterh:
a + b * c −→ a + ( b * c )
(o telest c * èqei megalÔterh proteraiìthta)
a + b - c −→ ( a + b ) - c
(Ðdia proteraiìthta allˆ arister  “omadopoÐhsh”)
• Kalì eÐnai na qrhsimopoioÔme parenjèseic, ( kai ), gia na
kˆnoume saf  th seirˆ thc apotÐmhshc
• Genikˆ h seirˆ apotÐmhshc den eÐnai egguhmènh
34

• Oi telestèc , , &&, || eggu¸ntai ìti to aristerì mèloc


touc ja apotimhjeÐ pr¸ta, p.q.
b = ( a = 2, a + 1 ) −→ b = 3 (ki ìqi b = 2)
• AÔxhsh kai MeÐwsh (ìpwc sth C) me touc telestèc ++ kai
--
– H èkfrash ++lvalue eÐnai isodÔnamh me thn èkfrash
lvalue += 1, isodÔnama lvalue = lvalue + 1,
(jewr¸ntac ìti to lvalue den èqei parenèrgeiec).
y = ++x −→ y = (x+=1)
y = x++ −→ y = (t=x,x+=1,t)
– Katˆ thn aÔxhsh/meÐwsh twn deikt¸n pou antistoiqoÔn
se array, to apotèlesma anafèretai sta stoiqeÐa tou
array (ki ìqi, p.q. stic dieujÔnseic). Gia parˆdeigma,
int p[] = {1,2,3,4};
int* q = p; cout << *q << endl;
q++; cout << *q << endl;
metˆ thn aÔxhsh, o q deÐqnei ston epìmeno akèraio (tou
array) ki ìqi sthn epìmenh jèsh mn mhc
35

Merikèc Parathr seic
• Den upˆrqoun entolèc anˆjeshc kai entolèc kl shc
sunˆrthshc: h anˆjesh kai h kl sh sunˆrthshc upˆgontai
sthn kathgorÐa twn ekfrˆsewn.
• Oi logikoÐ telestèc && kai || den apotimoÔn to deÔtero
ìrismˆ touc ektìc an eÐnai aparaÐthto.
• 'Opou gÐnontai èlegqoi tim¸n al jeiac eÐnai pio
euanˆgnwsto na grˆfoume rhtˆ tic logikèc ekfrˆseic, me
qr sh twn logik¸n telest¸n, parˆ na uponoeÐtai o
èlegqoc me bˆsh tic mh mhdenikèc timèc (mhn akoloujoÔme
thn prosèggish thc C na basizìmaste sthn mhdenik  h mh
mhdenik  tim  thc èkfrashc).
• Prosoq  stic proteraiìthtec! DeÐte to parakˆtw
prìgramma kai aitiologeÐste ti ektup¸nei:
#include <iostream.h>
// Inspired by an example in Eckel’ s book
main()
{
int a,b;

b=1;
cout << ((a = --b) ? b : (b = -99 ))
<< \n’ << " a is " << a
<< ’\n’ << " b is " << b << endl;

b=1;
cout << (a = --b ? b : (b = -99 ))
<< ’\n’ << " a is " << a
<< ’\n’ << " b is " << b << endl;
}
36

ENTOLES (à la C)
• Entolèc Epilog c (selection/choice):
– if ( expression ) statement
– if ( expression ) statement else statement
– switch ( expression ) statement
• Entolèc Epanˆlhyhc (iteration):
– while ( expression ) statement
– do statement while ( expression );
– for ( init-statement ; expression(opt) ; expression )
statement
• Entolèc Metaforˆc Elègqou (control):
– case constant-expression : statement
– default: statement
– break;
– continue;
– return expression(opt) ;
– goto identifier ;
• OnomasÐa Entol c: identifier : statement
37

Entolèc Epilog c (selection/choice)


• Epilog  if-then, sun jhc morf :
if (expression)
statement

• Epilog  if-then-else, sun jhc morf :


if (expression)
statement
else
statement

– H tim  thc èkfrashc expression mporeÐ na eÐnai true  


false
– To statement mporeÐ na antistoiqeÐ se mia mìno entol 
  se èna block entol¸n
• Pollapl  epilog  switch, sun jhc morf :
switch (selector)
{
case int1 : statement ; break ;
case int2 : statement ; break ;
....
default : statement ;
}

– H èkfrash selector parˆgei mia tim  akeraÐou


– Anˆloga me thn paragìmenh tim , o èlegqoc phgaÐnei
sto statement metˆ to antÐstoiqo case
– To break qreiˆzetai gia bgei o èlegqoc apì to switch
– to default upodeiknÔei ti prèpei na ektelesteÐ sthn
genik  perÐptwsh ìpou kanèna apì ta parapˆnw case de
mporeÐ na efarmosteÐ
38

Entolèc Epanˆlhyhc (iteration)


• Epanˆlhyh while, sun jhc morf :
while (expression)
statement

– H èkfrash expression apotimˆtai prin apì kˆje


epanˆlhyh tou statement
– H tim  thc èkfrashc expression mporeÐ na eÐnai true  
false
– To statement mporeÐ na antistoiqeÐ se mia mìno entol 
  se èna block entol¸n
39

– Parˆdeigma qr shc while kai switch - case

//: C03:Menu2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// A menu using a switch statement
#include <iostream>
using namespace std;

int main() {
bool quit = false; // Flag for quitting
while(quit == false) {
cout << "Select a, b, c or q to quit: ";
char response;
cin >> response;
switch(response) {
case ’a’ : cout << "you chose ’a’" << endl;
break;
case ’b’ : cout << "you chose ’b’" << endl;
break;
case ’c’ : cout << "you chose ’c’" << endl;
break;
case ’q’ : cout << "quitting menu" << endl;
quit = true;
break;
default : cout << "Please use a,b,c or q!"
<< endl;
}
}
} ///:~
40

• Epanˆlhyh for, sun jhc morf :


for(initialization; conditional; statementL)
statementB

– 'Otan mpaÐnei o èlegqoc sto for gia pr¸th forˆ,


ekteleÐtai to initialization ˆpax
– Prin apì kˆje epanˆlhyh, elègqetai an isqÔei to
conditional
– An eÐnai to conditional alhjèc, ekteleÐtai to
statementB
– Sto tèloc kˆje epanˆlhyhc (ˆma èqei oloklhrwjeÐ h
ektèlesh tou statementB ) ekteleÐtai to statementL
41

• Epanˆlhyh do-while, sun jhc morf :


do
statement
while (expression)

– To statement ekteleÐtai toulˆqiston mia forˆ, ìtan o


èlegqoc mpei sto do gia pr¸th forˆ
– H èkfrash expression apotimˆtai metˆ thn ektèlesh
tou statement
– Mia pijan  qr sh tou eÐnai sthn perÐptwsh pou h
èkfrash expression emplèkei timèc pou diabˆzontai
sto statement. Gia parˆdeigma, deÐte to parakˆtw
prìgramma:
//: C03:Guess2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// The guess program using do-while
#include <iostream>
using namespace std;

int main() {
int secret = 15;
int guess; // No initialization needed here
do {
cout << "guess the number: ";
cin >> guess; // Initialization happens
} while(guess != secret);
cout << "You got it!" << endl;
} ///:~
42

SUNARTHSEIS
• O trìpoc gia na “kˆnoume kˆti”.
• Mia sunˆrthsh den mporeÐ na klhjeÐ an den èqei dhlwjeÐ.
• Mia d lwsh sunˆrthshc perilambˆnei:
– to ìnoma thc sunˆrthshc
– ton tÔpo thc tim c pou epistrèfei
– to pl joc kai touc tÔpouc twn orismˆtwn thc
– p.q.
int sum(int i, int j);
void swap(int*, int*);

• Katˆ thn kl sh miac sunˆrthshc, h antimet¸pish eÐnai Ðdia


me thn arqikopoÐhsh twn orismˆtwn (ki ìqi me thn anˆjesh
tim¸n).
• Mia sunˆrthsh prèpei na orÐzetai mìno mia forˆ mèsa se
èna prìgramma.
• 'Otan kaleÐtai mia sunˆrthsh, oi q¸roi pou èqoun fulaqjeÐ
gia tic tupikèc paramètrouc thc arqikopoioÔntai me ta
antÐstoiqa orÐsmata.
• Epistrof  tim¸n: Ðdia diadikasÐa me thn arqikopoÐhsh
metablht¸n (mia entol  return leitourgeÐ san na
arqikopoieÐ mia metablht  tou tÔpou pou epistrèfei h
sunˆrthsh, sthn opoÐa dÐnetai h tim  thc èkfrashc thc
return, pragmatopoi¸ntac tic anˆlogec metatropèc
tÔpwn).
43

Uperfìrtwsh onomˆtwn sunart sewn


• “uperfìrtwsh” (  “epifìrtish”): overloading.
• Qr sh tou Ðdiou onìmatoc gia diaforetikèc sunart seic.
• Diˆkrish apì to pl joc/tÔpo twn orismˆtwn touc.
• O tÔpoc pou epistrèfei h sunˆrthsh den paÐzei rìlo gia th
diˆkrish.
• Upˆrqoun kanìnec pou upodeiknÔoun poio eÐnai to kalÔtero
taÐriasma tÔpwn katˆ thn kl sh miac sunˆrthshc.
• p.q.
void print(int) // for int
void print(const char*) // for strings
void print(double) ...
44

Default timèc orismˆtwn


• Gia thn perÐptwsh pou h genik  morf  thc kl shc miac
sunˆrthshc emplèkei perissìtera orÐsmata apì th morf 
twn suqnìterwn kl se¸n thc. p.q.
void print(int value, int base=10);
tìte
print(31) ---------> 31
print(31,10) ---------> 31
print(31,16) ---------> 1f
print(31,2) ---------> 11111

• Me qr sh enallaktik¸n orism¸n - epitreptì, lìgw


uperfìrtwshc - petuqaÐnoume to Ðdio apotèlesma. p.q.
void print(int value, int base);
void print(int value);
// me orismì gia ektÔpwsh sto 10dikì
• O èlegqoc tÔpwn twn default orismˆtwn gÐnetai sto
epÐpedo thc d lwshc en¸ h apotÐmhsh gÐnetai katˆ thn
kl sh thc sunˆrthshc.
• Den epitrèpontai default timèc se endiˆmesa orÐsmata. p.q.
OQI int g(int, int=0, int);
OUTE int g(int=0, int, int);
45

Gia parˆdeigma, an jèlame kˆti tètoio:


#include <iostream.h>

main()
{
int i = 16;

cout << "i in dec = " << i << endl;


cout << hex << "i in hex = " << i << endl;
cout << oct << "i in oct = " << i << endl;

me qr sh sunˆrthshc me default timèc orismˆtwn mporoÔme na


grˆyoume to ex c:
#include <iostream.h>
// the function void print(int,int) uses
//default value into its second argument

void print(int i, int base = 10)


{
switch(base) {
case (10) : cout << "i in dec = " << i << endl; break;
case (16) : cout << hex << "i in hex = " << i << endl; break;
case (8) : cout << oct << "i in oct = " << i << endl; break;
default : cout << "No proper base " << endl;
}
}

main()
{
int i = 16;

print(i);
print(i,16);
print(i,8);
}
46

Sunart seic inline
• Mia sunˆrthsh mporeÐ na oristeÐ wc inline dÐnontac mia
sumboul  sto metaglwttist , na bˆlei ton k¸dika thc
sunˆrthshc stic kl seic thc sunˆrthshc, antÐ na
qrhsimopoi sei ton klasikì mhqanismì kl shc
sunart sewn kai epistrof c apotelesmˆtwn. p.q.
inline int fac(int n) return (n<2?1:n*fac(n-1));
tìte, h kl sh fac(6), anˆloga me thn “exupnˆda” tou
metaglwttist , mporeÐ na gÐnei 6*5*4*3*2*1   760  
6*fac(5)   akìma kai na meÐnei anèpafh.
• Den eÐnai sÐgouro ìti kˆje inline sunˆrthsh ja
antimetwpisteÐ inline (p.q. amoibaÐa anadromikèc
sunart seic, sunart seic pou kaloÔn touc eautoÔc touc
anˆloga me thn eÐsodì touc klp.)
• H upìdeixh inline den parabiˆzei thn klasik  shmasÐa thc
kl shc sunˆrthshc. 'Ara, DEN EQOUME TIS
PARENERGEIES POU DHMIOURGOUNTAI APO
#define thc C.
• Oi sunart seic inline kai oi dhl¸seic const periorÐzoun
th qr sh #define sth C++.
47

Parˆdeigma gia parenèrgeiec thc #define - Asfal c qr sh me


inline sunart seic:
#include <iostream.h>

#define MAX1(i,j) (((i)>(j))?(i):(j))

inline int max2(int i, int j)


{ return ( i > j? i : j) ;}

main()
{
int m1, m2, i = 5, j = 10;

m2 = max2(i++,j++) ;

cout << "m2 = " << m2 << ’\n’;

cout << "i =" << i << endl;


cout << "j =" << j << endl;

m1 = MAX1(i++, j++);

cout << "m1 = " << m1 << ’\n’;


cout << "i = " << i << ’\n’;
cout << "j = " << j << ’\n’;
}

aitiolog ste ta apotelèsmata thc ektèleshc tou parapˆnw


progrˆmmatoc.
48

UpenjÔmish apì th C: OrÐsmata sth sunˆrthsh main.


Parˆdeigma:
#include <iostream.h>

int main(int argc, char* argv[])


{
cout << "argc = " << argc << endl;

for( int i=0 ; i < argc ; i++ )


cout << "argv[" << i << "] = " << argv[i] << endl;
}
49

STAJERES
• H lèxh-kleidÐ const mporeÐ na sumperilhfjeÐ se mia
d lwsh prosdiorist  (identifier) gia na ton metatrèyei se
stajerˆ antÐ gia metablht . P.q.
const int a = 5;

+-------+
a |// 5 //|
+-------+

to perieqìmeno tou a den mporeÐ na allˆxei


• Akrib¸c epeid  to perieqìmeno den mporeÐ na allˆxei, ènac
prosdiorist c pou dhl¸netai me const prèpei na
arqikopoieÐtai
• Telikˆ ki o metaglwttist c mporeÐ na ekmetalleuteÐ mia
d lwsh const (me diˆforouc trìpouc, anˆloga me to pìso
èxupnoc eÐnai)
50

Stajerèc kai DeÐktec


'Enac deÐkthc p pou deÐqnei kˆpou sth mn mh, sqhmatikˆ:

+------+
+--->| |
| +------+
|
|
|
+---|---+
p | |
+-------+

'Ara, èqoume diˆfora endeqìmena:


• D lwsh stajerˆc gia to antikeÐmeno sto opoÐo deÐqnei o
deÐkthc
const char* pc = "abcd";

+-------+
+--->|/|/|/|/|
| +-------+
|
|
|
+---|---+
pc | |
+-------+

Tìte,
pc[3] = ’a’; // error
51

• D lwsh stajerˆc gia to deÐkth


char *const cp = "abcd";
+-------+
+--->| | | | |
| +-------+
|
|
|
+---|---+
cp |///////|
+-------+

Tìte,
cp = "efgh"; // error
• D lwsh stajerˆc kai gia ta dÔo
const char *const cpc = "abcd";
+-------+
+--->|/|/|/|/|
| +-------+
|
|
|
+---|---+
cpc |///////|
+-------+

Tìte,
cpc[3] = ’a’; // error
cpc = "efgh"; // error
52

Gia na peiramatisteÐte, ektelèste to parakˆtw prìgramma:


#include <iostream.h>

main()
{
const int a = 10;
// a = 1000; // error
// a++; // error

const int arr[] = {1,2,3};


// arr[1] = 2000; // error

///////////////////////////////////////////////////////////////////
char abc[] = "abcdef";

const char* pc = abc; // pointer to constant

// pc[3] = ’a’; // error


// abc[3] = ’a’;
pc = "efghijkl"; // ok
///////////////////////////////////////////////////////////////////
char *const cp = abc; // constant pointer

cp[3] = ’a’; // ok
// cp = "efgh"; // error
///////////////////////////////////////////////////////////////////
const char *const cpc = abc; // constant pointer to constant
// cpc[3] = ’a’; // error
// cpc = "efgh"; // error
}
53

Parathr seic gia th qr sh tou const se sunduasmì me


deÐktec
• 'Ena antikeÐmeno to opoÐo eÐnai stajerˆ ìtan
prospelaÔnetai mèsw enìc deÐkth mporeÐ na eÐnai metablht 
ìtan prospelaÔnetai alli¸c (p.q. deÐkthc se stajerˆ san
ìrisma sunˆrthshc sto opoÐo pernˆ mh stajerˆ: to s¸ma
thc sunˆrthshc den metabˆllei to antikeÐmeno, to
peribˆllon apì to opoÐo kl jhke h sunˆrthsh kai sto
opoÐo ja epistrèyei o èlegqoc, ìmwc, mporeÐ)
• qr simo gia orÐsmata sunart sewn: dhl¸nontac èna ìrisma
pou eÐnai tÔpou deÐkth san const, h sunˆrthsh
apagoreÔetai na allˆxei to antikeÐmeno sto opoÐo deÐqnei.
Gia parˆdeigma,
char* strcpy(char* p, const char* q)
h sunˆrthsh den mporeÐ na allˆxei to antikeÐmeno sto
opoÐo deÐqnei to q
54

Pèrasma paramètrwn se sunart seic pou allˆzoun to


“exwterikì” antikeÐmeno
• Pèrasma paramètrwn à la C:
void swap(int* p, int* q)
{
int t = *p ;
*p = *q ;
*q = t ;
}
Kl sh:
int i, j;
swap(&i, &j);

• Pèrasma paramètrwn à la C++


void swap(int& r1, int& r2)
{
int t = r1 ;
r1 = r2 ;
r2 = t ;
}
Kl sh:
int i, j;
swap(i, j);
55

Timèc - DeÐktec ... kai ANAFORES (references)


• SugkrÐnete ta parakˆtw kommˆtia k¸dika kai to
apotèlesma touc sthn mn mh
int i, j; +-------+
i | 3 |
i = 3; +-------+

j = i; +-------+
j | 3 |
+-------+
+---------+ j
int i; |+-------+| |
i || 3 ||<--+
i = 3; |+-------+|
+---------+

int &j = i;
Sth deÔterh perÐptwsh, to j eÐnai “sun¸numo” tou i, mìno
pou ìtan lème i anaferìmaste sthn tim  thc metablht c i
en¸ ìtan lème j anaferìmaste sto q¸ro (sthn ontìthta)
pou katalambˆnei h metablht  j (dhlad  h i).
• Oi anaforèc sumperifèrontai san stajeroÐ deÐktec proc to
antikeÐmeno me to opoÐo arqikopoioÔntai (ˆra pˆnta prèpei
na arqikopoioÔntai) kai den qreiˆzontai dereferencing
56

• Prosoq , o telest c & exakoloujeÐ na qrhsimopoieÐtai kai


gia na ekfrˆsoume th dieÔjunsh miac metablht c.
SugkrÐnete ta prohgoÔmena me to:
+--------+
int i; i +->| |
| +--------+
int* p; |
|
p = &i; +---|---+
p | |
+-------+
57

'Allec parathr seic gia tic anaforèc


• Sth genik  perÐptwsh, ta orÐsmata sunart sewn pernˆne
mèsw tim¸n. p.q.
void f(int val) main | f
---------+-------
|
... |
+---+ | +---+
int i=5; i | 5 | | | 5 | val
f(i); +---+ | +---+
|

MporoÔme na perˆsoume deÐkth: se aut n thn perÐptwsh


èqoume ˆmesh prìsbash sto “exwterikì” antikeÐmeno apì
th sunˆrthsh, allˆ o k¸dikac gÐnetai polÔplokoc.
• PetuqaÐnoume to Ðdio apotèlesma, an perˆsoume anaforˆ
sto “exwterikì”antikeÐmeno. p.q.
void f(int& val) main | f
---------+-------
|
... |
+---+ | +---+
int i=5; i | 5 |<------+ | val
f(i); +---+ | +---+
|

• Megˆla antikeÐmena kalì eÐnai na ta pernˆme mèsw


anaforˆc, gia lìgouc apodotikìthtac.
• Akìma ki an den èqoume prìjesh na allˆxoume thn tim 
touc, to parapˆnw isqÔei. Se aut n thn perÐptwsh ìmwc,
kalì eÐnai na periorÐzoume thn anaforˆ me const. p.q.
void f(const tree& t)
{...}

opìte, sto s¸ma thc f apagoreÔetai na allˆxei h tim  tou


t.
• Ta arrays pernˆne mèsw anafor¸n.
58

Metablhtèc: aplèc, anaforèc kai deÐktec


PeiramatisteÐte me ta parakˆtw progrˆmmata:
#include <iostream.h>

main()
{
int i,j;
i=5;
j=i;
cout << j << ’\n’ << i << ’\n’;
cout << & j << ’\n’ << & i << ’\n’;

int ii;
ii = 3;
int & jj = ii;
cout << jj << ’\n’ << ii << ’\n’;
cout << & jj << ’\n’ << & ii << ’\n’;

int* p;
int* q;
p = & ii;
q = & jj;

cout << p << ’\n’ << q << ’\n’;


}
Parathr ste ìti kai akìma ìtan milˆme gia th dieÔjunsh thc
anaforˆc, telikˆ prospelaÔnoume th dieÔjunsh thc metablht c me
thn opoÐa desmeÔsame thn anaforˆ.
#include <iostream.h>

main()
{

int i;
int &j = i;

i = 3;

int* p = &j;

cout << p << ’\n’ << &j << ’\n’ << &i << endl ;
}
59

Pèrasma paramètrwn se sunˆrthsh: paradeÐgmata


• Me ton trìpo thc C
//: C03:PassAddress.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;

void f(int* p) {
cout << "p = " << p << endl;
cout << "*p = " << *p << endl;
*p = 5;
cout << "p = " << p << endl;
}

int main() {
int x = 47;
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
f(&x);
cout << "x = " << x << endl;
} ///:~
60

• Me ton trìpo thc C++


//: C03:PassReference.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
using namespace std;

void f(int& r) {
cout << "r = " << r << endl;
cout << "&r = " << &r << endl;
r = 5;
cout << "r = " << r << endl;
}

int main() {
int x = 47;
cout << "x = " << x << endl;
cout << "&x = " << &x << endl;
f(x); // Looks like pass-by-value,
// is actually pass by reference
cout << "x = " << x << endl;
} ///:~
61

OI TELESTES new KAI delete


Dèsmeush q¸rou sth mn mh:
static metablhtèc O q¸roc touc anatÐjetai ìtan arqÐzei h
ektèlesh tou progrˆmmatoc kai diathreÐtai kaj’ ìlh thn
ektèles  tou.
automatic metablhtèc O q¸roc touc anatÐjetai kˆje forˆ
pou o èlegqoc thc ektèleshc ftˆnei ston orismì touc kai
diathreÐtai èwc ìtou o èlegqoc bgei apì to block mèsa sto
opoÐo upˆrqei o orismìc.
dunamik  dèsmeush Katˆ thn ektèlesh enìc progrˆmmatoc,
gia na dhmiourg soume antikeÐmena rhtˆ ta opoÐa
katalambˆnoun kˆpoio q¸ro èwc ìtou rhtˆ na ton
apodesmeÔsoun, qrhsimopoioÔme touc telestèc new kai
delete.
• me ton telest  new dhmiourgoÔme tètoia antikeÐmena
• me ton telest  delete ta katastrèfoume
• den upˆrqei garbage collection gia tètoia antikeÐmena ki
ètsi prèpei na prosèqoume na apodesmeÔoume to q¸ro
• touc qrhsimopoioÔme se peript¸seic pou, p.q. jèloume
na dhmiourgoÔme “domikˆ stoiqeÐa” miac megalÔterhc
dom c pou de xèroume to mègejìc thc katˆ th fˆsh thc
metagl¸ttishc. p.q. kìmboi dèndrwn, stoiqeÐa lÐstac
62

Metablhtèc ston statikì (static) kai sto


metaballìmeno q¸ro (stack): PeiramatisteÐte ektel¸ntac
ta parakˆtw progrˆmmata kai aitiologeÐste ta apotelèsmata
(“sqediˆste” touc q¸rouc thc mn mhc).
• Parˆdeigma
int i = 1000; // global scope, allocated in static space

void g()
{
int i = 5; // scope within g, automatic variable
}

void f()
{
int i = 50; // scope within f, automatic variable
static int j = 500; // scope within f, allocated in static space

g();
}

main()
{
int i = 5000; // scope within main, automatic variable

f();
}

• Parˆdeigma
//File: vars.cc
#include <iostream.h>
int g = 1000;

void p(int i)
{
int j = 30;
cout << "i in p is : " << i << endl;
cout << "j in p is : " << j << "\n\n\n" << endl;
}
63

void f(int i)
{
int j = 20;
static int k = 100;

cout << "i in f is : " << i << endl;


cout << "j in f is : " << j << endl;

cout << "k in f is : " << k << endl;

cout << "g in f is : " << g << "\n\n" << endl;

i++; j++; k++; g++;

p(i);
}

int main()
{
int i = 5;
cout << "i in main is :" << i << ’\n’ << endl;
f(i);
cout << "i in main is :" << i << ’\n’ << endl;
f(i++);
cout << "i in main is :" << i << ’\n’ << endl;
f(++i);
cout << "i in main is :" << i << ’\n’ << endl;

cout << "g in main is :" << g << ’\n’ << endl;
}
64

Dèsmeush ston eleÔjero q¸ro (heap): PeiramatisteÐte


ektel¸ntac ta parakˆtw progrˆmmata kai aitiologeÐste ta
apotelèsmata (“sqediˆste” touc q¸rouc thc mn mhc).
• Parˆdeigma (tropopoÐhsh tou prohgoÔmenou ¸ste na gÐnetai
dunamik  dèsmeush q¸rou sto s¸ma thc sunˆrthshc p).
// Similar to vars.cc but space allocated within the body of function p
#include <iostream.h>

int g = 1000;

void p(int i)
{
int* j = new int(30); // now j points to heap

cout << "i in p is : " << i << endl;


cout << "j in p points to : " << *j << "\n\n\n" << endl;

delete j;
}

void f(int i)
{
int j = 20;

static int k = 100;

cout << "i in f is : " << i << endl;


cout << "j in f is : " << j << endl;

cout << "k in f is : " << k << endl;

cout << "g in f is : " << g << "\n\n" << endl;

i++; j++; k++; g++;

p(i);
}
65

int main()
{
int i = 5;

cout << "i in main is :" << i << ’\n’ << endl;
f(i);
cout << "i in main is :" << i << ’\n’ << endl;
f(i++);
cout << "i in main is :" << i << ’\n’ << endl;
f(++i);
cout << "i in main is :" << i << ’\n’ << endl;

cout << "g in main is :" << g << ’\n’ << endl;
}
66

• Parˆdeigma: lifetime kai embèleiac (q¸roc pou desmeÔthke


dunamikˆ apodesmeÔetai allˆ o deÐkthc pou arqikopoi jhke na
deÐqnei se autìn paramènei sthn embèleia).
#include <iostream.h>

void p()
{
int k = 300;
int* kk = &k;
cout << "kk points to :" << *kk << "\n\n\n" << endl;

int* j = new int(30);


cout << "j in p points to : " << *j << "\n\n\n" << endl;

delete j; // deallocate storage where j pointed to;

j = kk; // j is NOT out of scope, now poins where kk points to

cout << "kk points to :" << *kk << "\n\n\n" << endl;
cout << "j after deletion points to :" << *j << "\n\n\n" << endl;
}

int main()
{
p(); p();
}
67

'Allec parathr seic pˆnw sth dunamik  dèsmeush kai


apodèsmeush q¸rou
• O telest c new epistrèfei deÐkth se antikeÐmeno tou tÔpou
pou prosdiorÐzoume. p.q.
node* n = new node;
ShmeÐwsh: an to node èqei oristeÐ san klˆsh, katˆ th
dèsmeush tou q¸rou ston heap kaleÐtai o constructor thc
klˆshc (bl. Klˆseic)
• O telest c delete prèpei na efarmìzetai se deÐktec pou
epestrˆfhsan apì efarmog  tou telest  new, p.q. sto
deÐkth pou orÐsthke sto parapˆnw
delete n;
ShmeÐwsh: an to node èqei oristeÐ san klˆsh, kaleÐtai o
destructor thc klˆshc (bl. Klˆseic)
• MporoÔme na dhmiourg soume/katastrèyoume arrays apì
antikeÐmena qrhsimopoi¸ntac touc telestèc new kai
delete. p.q.
char* s = new char[10];
delete[] s;
ShmeÐwsh: an ta stoiqeÐa tou array eÐnai antikeÐmena
klˆshc, gia kajèna apì autˆ, kaleÐtai o default
constructor thc klˆshc (bl. Klˆseic)
• ArqikopoÐhsh katˆ th dunamik  dhmiourgÐa:
int* pi = new int(1024);
Prosoq :
– An èqoume: int* pi = new int(1024);
68

pi deÐkthc se akèraio o opoÐoc akèraioc arqikopoieÐtai


me thn tim  1024. Gia na apodesmeÔsoume to q¸ro arkeÐ
na kˆnoume: delete pi;
– En¸, an èqoume: int* pia = new int[1024];
dhmiourgÐa enìc array deikt¸n se akèraio to opoÐo èqei
mègejoc 1024. Gia na apodesmeÔsoume to q¸ro prèpei
na kˆnoume: delete[] pia;
69

'Ena aplì parˆdeigma diadikastikoÔ programmatismoÔ me C++:


diagraf  qarakt ra apì mia akoloujÐa qarakt rwn
• me epistrof  tou apotelèsmatoc sthn arqik  akoloujÐa
#include <iostream.h>

void remove(char*,char);

main()
{
char string1[] = "abagaadagaga";
char string2[] = "abagaadagaga";
char string3[] = "ccabbbb";

remove(string1, ’a’);
cout << string1 <<endl;

remove(string2, ’g’);
cout << string2 <<endl;

remove(string3, ’a’);
cout << string3 <<endl;
}

void remove(char* str, char ch)


{
int i=0, j=0;
while (str[j] != ’\0’)
{
while (str[j] != ch && str[j] != ’\0’)
str[i++] = str[j++];
while (str[j] == ch)
j++;
}
str[i] = ’\0’;
}

• me dhmiourgÐa nèac akoloujÐac


#include <iostream.h>

int length(const char* str)


{
int length;
70

for(int i = 0; str[i] != ’\0’; i++)


length = i;

return length;
}

char* remove(const char*,char);

main()
{
char* string1 = "abagaadagaga";

cout << remove(string1, ’a’) <<endl;


cout << remove(string1, ’g’) <<endl;
}

char* remove(const char* str, char ch)


{
int l = length(str);

char* res = new char[l+1];

for( int i =0, j = 0; i <= l; i++ )


if ( str[i] != ch )
{
res[j] = str[i] ;
j++;
}
return res;
}
• Problhmatik  ulopoÐhsh: esfalmènh anaforˆ se mn mh
#include <iostream.h>

int length(const char* str)


{
int length;
for(int i = 0; str[i] != ’\0’; i++)
length = i;
return length;
}

char* remove(const char*,char);


71

main()
{
char* string1 = "abagaadagaga";

cout << remove(string1, ’a’) <<endl;


cout << remove(string1, ’g’) <<endl;

char* remove(const char* str, char ch)


{
int l = length(str);

char res[l+1];

for( int i =0, j = 0; i <= l; i++ )


if ( str[i] != ch )
{
res[j] = str[i] ;
j++;
}
return res; //error: when returning from remove, res out of scope
//and its space is "discarted" from the stack
}
72

Genikèc Parathr seic perÐ Metagl¸ttishc kai


Sundesimìthtac Programmˆtwn C++
• 'Ena C++ prìgramma eÐnai èna sÔnolo sunart sewn me
toulˆqisto mia sunˆrthsh, th sunˆrthsh main
• Oi sunart seic efarmìzontai pˆnw se dedomèna-metablhtèc
pou an koun se (built-in   user-defined) tÔpouc
• H ektèlesh enìc progrˆmmatoc C++ xekinˆ kal¸ntac th
sunˆrthsh main. H kl sh aut  eisˆgetai autìmata katˆ
thn kataskeu  tou ektelèsimou arqeÐou tou progrˆmmatoc.
• To phgaÐo C++ prìgramma mporeÐ na eÐnai grammèno se
èna   perissìtera arqeÐa
• H monˆda metagl¸ttishc eÐnai èna arqeÐo (den mporoÔme na
metaglwttÐsoume kˆti ligìtero, p.q. mia sunˆrthsh: an
jèloume na metaglwttÐsoume mìno aut n, ac th grˆyoume
se èna arqeÐo)
• Ta arqeÐa ta opoÐa summetèqoun sthn entol 
metagl¸ttishc perièqoun k¸dika sunart sewn kai orismoÔc
metablht¸n kai eÐnai ta arqeÐa k¸dika (katˆlhxh .cc,
.cpp)
• Ta arqeÐa k¸dika mporeÐ na kˆnoun include arqeÐa
-epikefalÐdec (header files)
• Sta arqeÐa-epikefalÐdec grˆfoume dhl¸seic (ìqi k¸dika
sunart sewn   orismoÔc metablht¸n) ektìc apì eidikèc
peript¸seic (const metablhtèc, inline sunart seic) kai
orismoÔc tÔpwn kai q¸rwn onomˆtwn
• Kˆje ìnoma (metablht c, sunˆrthshc, tÔpou klp.) prèpei
73

na èqei dhlwjeÐ prin na qrhsimopoihjeÐ mèsa se èna arqeÐo


(ìqi aparaÐthta na oristeÐ)
• Tìso oi metablhtèc enìc progrˆmmatoc ìso kai ta s¸mata
twn orism¸n twn sunart sewn katalambˆnoun q¸ro sth
mn mh
• O orismìc miac metablht c, dhlad  h èkfrash ekeÐnh pou
odhgeÐ se dèsmeush q¸rou sth mn mh gia th metablht 
aut , prèpei na upˆrqei akrib¸c mia forˆ se ìlo to
prìgramma (ektìc an prìkeitai gia metablhtèc pou an koun
se diaforetikèc embèleiec, ˆra ˆllec metablhtèc)
• O orismìc miac sunˆrthshc gÐnetai me to na oristeÐ kai to
s¸ma thc sunˆrthshc, dhlad  o k¸dikˆc thc
• O orismìc miac sunˆrthshc prèpei na upˆrqei akrib¸c mia
forˆ se ìlo to prìgramma (ektìc an prìkeitai gia
uperfortwmènouc orismoÔc)
74

Sundesimìthta - embèleia metablht¸n


Kajolikèc metablhtèc : Mia kajolik  metablht 
• orÐzetai se èna arqeÐo, èxw apì opoiad pote sunˆrthsh
• èqei exwterik  sundesimìthta, dhlad  mporeÐ na
qrhsimopoihjeÐ apì opoud pote sto prìgramma
----------------------------------
| |
\|/ f1.cpp f2.cpp |
+----------+ +--------------+
| | | |
|int i; | |extern int i; |
| | | |
| ...... | | ...... |
| | | |
+----------+ +--------------+

Sto arqeÐo f1.cpp gÐnetai o orismìc thc metablht c i.


Sto arqeÐo f2.cpp upˆrqei apl¸c mia d lwsh gia thn
metablht  i.
Statikèc metablhtèc : Mia statik  metablht 
• orÐzetai se èna arqeÐo, èxw apì opoiad pote sunˆrthsh
kai proshmaÐnetai me th lèxh-kleidÐ static
• èqei eswterik  sundesimìthta, dhlad  mporeÐ na
qrhsimopoihjeÐ mìno mèsa sto arqeÐo
f1.cpp f2.cpp
+--------------+ +--------------+
| | | |
|static int i; | |extern int i; |
| | | |
| ...... | | ...... |
| | | |
+--------------+ +--------------+

Sto arqeÐo f1.cpp gÐnetai o orismìc thc metablht c i.


Sto arqeÐo f2.cpp upˆrqei mia d lwsh gia mia
metablht  i ìmwc gia thn i aut  den upˆrqei poujenˆ
orismìc.
75

Metablhtèc const : Mia metablht  const


• an oristeÐ èxw apì sunˆrthsh, èqei eswterik 
sundesimìthta (de mporeÐ na prospelajeÐ apì ˆlla
arqeÐa)
• gia na apokt sei exwterik  sundesimìthta prèpei ston
orismì thc na proshmanjeÐ kai me th lèxh-kleidÐ extern
Statikèc metablhtèc topikèc se sunˆrthsh : Mia
statik  metablht  topik  se sunˆrthsh
• orÐzetai mèsa sto s¸ma miac sunˆrthshc, proshmènetai
me th lèxh -kleidÐ static kai ofeÐlei na arqikopoieÐtai
• ufÐstatai èwc to tèloc ìlwn twn kl sewn thc
sunˆrthshc kai diathreÐ thn tim  thc anˆmesa stic
kl seic
Autìmatec (topikèc) metablhtèc : Mia autìmath
metablht 
• orÐzetai mèsa sto s¸ma miac sunˆrthshc, endeqìmena
kai se eswterikì block
• dhmiourgeÐtai proswrinˆ, mèsa sth stoÐba (stack) kai
katastrèfetai mìlic o èlegqoc thc ektèleshc bgei apì
th sunˆrthsh (  to block) ìpou ègine o orismìc thc
• den èqei kajìlou sundesimìthta, o linker den asqoleÐtai
me tic topikèc metablhtèc
Dunamik  dhmiourgÐa kai katastrof  metablht¸n katˆ
thn ektèlesh enìc progrˆmmatoc:
• dhmiourgoÔntai me th qr sh tou telest  new
• o q¸roc pou touc anatÐjetai brÐsketai sto swrì (heap)
• prèpei na katastrafoÔn rhtˆ me qr sh tou telest 
76

delete alli¸c desmeÔoun to q¸ro èwc to tèloc


ektèleshc tou progrˆmmatoc
Parathr seic:
• Ta parapˆnw den kˆnoun anaforˆ se metablhtèc embèleiac
klˆshc oÔte kai q¸rou onomˆtwn.
• Ta statikˆ mèlh -dedomèna twn klˆsewn desmeÔontai ston
statikì q¸ro kai èqoun embèleia klˆshc.
77

Sundesimìthta - embèleia sunart sewn


• Oi sunart seic èqoun exwterik  sundesimìthta kai
mporoÔn na qrhsimopoihjoÔn apì k¸dika pou brÐsketai se
opoiod pote arqeÐo tou progrˆmmatoc
• Gia na apokt sei mia sunˆrthsh eswterik  sundesimìthta
kai na mhn mporeÐ na qrhsimopoihjeÐ èxw apì to arqeÐo sto
opoÐo orÐzetai prèpei na proshmanjeÐ me th lèxh -kleidÐ
static
• Oi sunart seic inline èqoun eswterik  sundesimìthta.
Parat rhsh: Ta parapˆnw den kˆnoun anaforˆ se sunart seic
embèleiac klˆshc oÔte kai q¸rou onomˆtwn.
78

EISODOS - EXODOS sth C++


• <iostream.h> (<iostream>): arqeÐo-epikefalÐda gia tic
perissìterec leitourgÐec I/O thc C++ (diepaf  me th
biblioj kh gia to qeirismì reumˆtwn, streams)
• Antikeimenostraf c filosofÐa I/O sth C++
• Morfopoihmènh I/O
• I/O qarakt rwn
• I/O pˆnw se arqeÐa
• I/O in RAM
79

Krit ria gia to sqediasmì tou sust matoc I/O thc


C++
• Stic “paradosiakèc” gl¸ssec programmatismoÔ, to
sÔsthma I/O eÐqe na uposthrÐxei èna peperasmèno sÔnolo
apì enswmatwmènouc tÔpouc.
• Sth C++ to sÔnolo twn tÔpwn eÐnai epektˆsimo apì touc
tÔpouc pou orÐzei o qr sthc.
• To sÔsthma I/O thc C++ eÐnai eÔkolo sth qr sh, pl rec,
apotelesmatikì ALLA KAI asfalèc sto qeirismì tÔpwn
kai euèlikto.
ReÔmata
• To sÔsthma I/O thc C++ leitourgeÐ mèsw reumˆtwn
(streams).
• 'Ena reÔma eÐnai mia logik  suskeu  pou eÐte parˆgei eÐte
katanal¸nei plhroforÐa.
• 'Ena reÔma sundèetai me mia fusik  suskeu , mèsa apì to
sÔsthma I/O thc C++.
• Ta reÔmata, ousiastikˆ, eÐnai stigmiìtupa twn klˆsewn
istream, ostream, iosream - , ìpwc ja doÔme parakˆtw,
upoklˆse¸n touc -.
• 'Otan èna prìgramma C++ xekinˆ thn ektèles  tou,
“anoÐgoun” ta enswmatwmèna reÔmata:
cin: prokajorismènh eÐsodoc (standard input)
cout: prokajorismènh èxodoc (standard output)
cerr,clog: prokajorismènh èxodoc sfalmˆtwn
To pr¸to antistoiqeÐ sto plhktrolìgio kai ta ˆlla dÔo
sthn ojình ektìc an èqei gÐnei anakateÔjunsh.
80

EÐsodoc/Exodoc Metablht¸n
'Exodoc metablht¸n : me qr sh tou telest  <<
• Genik  morf : <ReÔmaExìdou> << <Metablht >
• P.q.
int i = 10;
cout << i;
EÐsodoc metablht¸n : me qr sh tou telest  >>
• Genik  morf : <ReÔmaEisìdou> >> <Metablht >
• P.q.
float f ;
cin >> f;
• Sthn èkfrash eisìdou   exìdou, de dÐnetai kamiˆ
plhroforÐa gia ton tÔpo thc metablht c. To epijumhtì
apotèlesma epitugqˆnetai lìgw twn uperfortwmènwn
orism¸n twn telest¸n << kai >>.
• Dedomènou ìti oi telestèc << kai >> epistrèfoun reÔma
exìdou kai reÔma eisìdou, antÐstoiqa, mporoÔme na touc
qrhsimopoi soume perissìterec apì mia forˆ se mia
èkfrash.
81

ParadeÐgmata
#include <iostream.h>

main()
{
int i;
cin >> i;

float f;
cin >> f;

char c;
cin >> c;

char buf[10];
cin >> buf;

cout << "i = " << i << endl;


cout << "f = " << f << endl;
cout << "c = " << c << endl;
cout << "buf = " << buf << endl;
}

To Ðdio epitugqˆnoume me to parakˆtw:


#include <iostream.h>

main()
{
int i;
float f;
char c;
char buf[10];

cin >> i >> f >> c >> buf;

cout << "i = " << i << endl;


cout << "f = " << f << endl;
cout << "c = " << c << endl;
cout << "buf = " << buf << endl;
}
82

MorfopoÐhsh Eisìdou/Exìdou MporeÐ na gÐnei me dÔo


trìpouc:
1. Me qr sh sunart sewn-mel¸n thc klˆshc ios kai qeirismì
shmai¸n (flags).
2. Me qr sh “diamorfwt¸n” (manipulators).
83

Diamorfwtèc (manipulators)
• Gia na grˆfoume sthn Ðdia gramm  eisìdou   exìdou tic
leitourgÐec pou jèloume na gÐnoun.
• Orismìc sunart sewn pou lègontai diamorfwtèc kai
mporoÔn na perilhfjoÔn stic ekfrˆseic I/O.
• Genik  morf :
ostream& < manip name >(ostream& < stream >)
istream& < manip name >(istream& < stream >)
ostream& < manip name >(ostream& < stream >,
< type param >)
...
• MporoÔn na oristoÔn kai apì to qr sth (lìgw
upost rixhc uperfìrtwshc)
84

Enswmatwmènoi Diamorfwtèc
dec: input/output data in decimal (input/output)
hex: input/output data in hexadecimal (input/output)
oct: input/output data in octal (input/output)
endl: output nl and flush the stream (output)
ends: output nl (output)
flush: flush the stream (output)
ws: skip leading whitespace (input)
resetiosflags(long f): turn off flags specified in "f"
(input/output)
setbase(int base): set the number base to "base" (output)
setfill(int ch): set fill character to "ch" (output)
setiosflags(long f): turn on the flags specified in "f"
(input/output)
setprecision(int p): set the number of digits of precision
(output)
setw(int w): set the field width to "w" (output)
...

Parathr seic:
• Gia touc diamorfwtèc pou den èqoun orÐsmata den prèpei na
bˆzoume parenjèseic.
• Gia na qrhsimopoi soume touc diamorfwtèc pou èqoun
orÐsmata prèpei na perilˆboume to arqeÐo -epikefalÐda
<iomanip.h> (<iomanip>).
85

EÐsodoc/'Exodoc se EpÐpedo Qarakt rwn


EÐsodoc (mèsw sunart sewn-mel¸n thc istream)
• basic istream& get(char& ch) : diabˆzei ènan
qarakt ra kai ton topojeteÐ sto ch. p.q. char ch;
cin.get(ch); Sthn perÐptwsh pou ftˆsoume sto tèloc
tou arqeÐou, h kl sh thc get epistrèfei tim  (pou
antistoiqeÐ se) false.
• basic istream& get(char* buf, int num, char
delim=’\n’): diabˆzei qarakt rec kai touc topojeteÐ
ston pÐnaka ston opoÐo deÐqnei h buf èwc ìtou eÐte
diabastoÔn num-1 qarakt rec eÐte ftˆsoume se delim.
O pÐnakac ston opoÐo deÐqnei h buf ja termatisteÐ me
null. To delim den afaireÐtai apì to reÔma (ja to
epexergasteÐ h epìmenh diadikasÐa eisìdou)
• int get(): epistrèfei ton epìmeno qarakt ra apì to
reÔma eisìdou (epistrèfei EOF an èftase sto tèloc tou
arqeÐou)
• bool eof(): gia èlegqo an ftˆsame sto tèloc tou
arqeÐou
• basic istream& getline(char* buf, int num,
char delim=’\n’): san thn antÐstoiqh get ektìc tou
ìti to delim diabˆzetai kai afaireÐtai apì to reÔma
eisìdou.
• basic istream& read(unsigned char* buf, int
num): gia na diabˆsoume èna mplok num qarakt rwn kai
na to bˆloume ston pÐnaka pou deÐqnei h buf.
• Gia anˆgnwsh qarakt rwn antÐstoiqh me thn read(),
mporeÐ na qrhsimopoihjeÐ h ignore(). Se aut n thn
86

perÐptwsh, oi qarakt rec pou diabˆsthkan den


fulˆssontai poujenˆ.
'Exodoc (mèsw sunart sewn -mel¸n thc ostream)
• basic ostream& put(char ch): grˆfei to qarakt ra
ch sto reÔma exìdou.
• basic ostream& write(const unsigned char* buf,
int num): grˆfei num qarakt rec sto reÔma exìdou
apì ton pÐnaka ston opoÐo deÐqnei h buf.
'Elegqoc problhmˆtwn gia opoiod pote stigmiìtupo thc
iostream: good(), bad(), eof(), fail() (basÐzontai sta
eofbit, failbit, badbit pou eÐnai orismèna sthn ios kai
elègqoun thn katˆstash twn reumˆtwn)

'Elegqoc thc Katˆstashc ReÔmatoc

Anˆ pˆsa stigm , kˆje reÔma brÐsketai se mia “katˆstash”


(state). H katˆstash aut  mporeÐ na elegqjeÐ mèsw twn
parakˆtw sunart sewn-mel¸n thc ios:
bool good() const;: h epìmenh prˆxh endèqetai na petÔqei
bool eof() const;: h eÐsodoc èftase sto tèloc
bool fail() const;: h epomènh prˆxh ja apotÔqei
bool bad() const; : to reÔma èqei qalˆsei
'Otan èna reÔma qrhsimopoieÐtai se mÐa sunj kh, ousiastikˆ,
elègqetai h katˆstas  tou me bˆsh kl sh sthn fail().
87

EÐsodoc/'Exodoc pˆnw se ArqeÐa


• <fstream.h> (<fstream>): arqeÐo -epikefalÐda pou prèpei
na perilˆboume an jèloume na kˆnoume eÐsodo   èxodo apì
kai proc arqeÐa.
• OrÐzoun diˆforec klˆseic metaxÔ twn opoÐwn kai tic:
ifstream: gia eÐsodo
ofstream: gia èxodo
fstream: gia eÐsodo kai èxodo
san upoklˆseic twn klˆsewn istream kai ostream.
• ìti mporoÔme na kˆnoume se istream kai ostream mporoÔme
na kˆnoume kai se ifstream kai ofstream kai mˆlista
• ìti mporoÔme na kˆnoume kai apì thn ios mporoÔme na to
efarmìsoume kai sta arqeÐa.

Anoigma/KleÐsimo arqeÐwn
• AnoÐgoume èna arqeÐo sundèontˆc to me èna reÔma.
• Ta reÔmata eÐnai stigmiìtupa twn klˆsewn ifstream,
ofstream, fstream.
• void open(const char* filename, int mode, int
access=filebuf::openprot), ìpou
– filename: to ìnoma tou arqeÐou pou anoÐgoume
– mode: mia apì tic ios::app, ios::ate, ios::binary,
– ios::in, ios::nocreate, ios::noreplace, ios::out,
ios::trunc (mporoÔn na sunduastoÔn me OR)
– access, arketˆ qamhloÔ epipèdou, sqedìn pˆnta paÐrnei
th default tim 
88

• An apotÔqei h open, to reÔma paÐrnei thn tim  mhdèn


(klasikìc trìpoc elègqou an ìla p gan kalˆ me to
ˆnoigma).
• Gia na kleÐsoume èna arqeÐo qrhsimopoioÔme close() , p.q.
datast.close();
ìmwc, den eÐnai upoqrewtikì na to kˆnoume rhtˆ mia pou
autì gÐnetai autìmata apì th sunˆrthsh katastrof c ìtan
bgaÐnoume apì thn embèleia tou reÔmatoc.
• Epeid  oi klˆseic ofstream, ifstream, fstream èqoun
sunart seic kataskeu c stigmiotÔpwn pou kaloÔn thn
open, tic perissìterec forèc den eÐnai anˆgkh na anoÐgoume
ta arqeÐa rhtˆ. ArkeÐ, p.q.
ifstream datastr("DATAFILE");
me autì tautìqrona kˆname:
– d lwsh gia reÔma datastr
– sÔndesh me to arqeÐo DATAFILE
– ˆnoigma gia diˆbasma
• Prìsjetec dunatìthtec:
– tuqaÐa prospèlash
– qeirismìc/fÔlaxh trèqousac jèshc
– ...
89

ParadeÐgmata:
• 'Exodoc metablht¸n se arqeÐo
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream out("test");
if (!out) {
cout << "Cannot open file.\n";
return 1;
}

out << 10 << " " << 123.23 << "\n";


out << "This is a short text file.";

out.close();
return 0;
}
• EÐsodoc metablht¸n apì arqeÐo
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
char ch; int i; float f; char str[80];

ifstream in("test");
if(!in) {
cout << "Cannot open file.\n";
return 1;
}
in >> i >> f >> ch >> str;

cout << i << " " << f << " " << ch << endl;
cout << str << endl;

in.close();
return 0;
}
90

• Kataskeu  antigrˆfou perieqomènwn arqeÐou


#include <fstream>

void error(const char* p, const char* p2 = "")


{
cerr << p << ’ ’ << p2 << ’\n’;
std::exit(1);
}

int main(int argc, char* argv[])


{
if (argc != 3) error("wrong number of arguments");

std::ifstream from(argv[1]); // open input file stream


if (!from) error("cannot open input file", argv[1]);

std::ofstream to(argv[2]); // open output file stream


if (!to) error("cannot open output file", argv[2]);

char ch;
while (from.get(ch)) to.put(ch); // copy characters

if (!from.eof() || !to) error("something strange happened");


}
91

EÐsodoc/'Exodoc apì PÐnakec


• ArqeÐo -epikefalÐda <strstrea.h> (strstrea)
• Qr sh thc RAM gia eÐsodo/èxodo
• Anˆlogh prosèggish me th C (sprintf(), sscanf())
• Me qr sh reumˆtwn
92

Antikeimenostraf c Prosèggish tou Sust matoc I/O


• Klˆsh: ios (upoklˆsh thc ios base)
• H klˆsh ios prosfèrei leitourgÐec gia morfopoihmènh
eÐsodo kai èxodo.
• Upoklˆseic: istream, ostream (upoklˆsh touc:
iostream)
– Upoklˆseic thc istream: ifstream, istringstream
– Upoklˆseic thc ostream: ofstream, ostringstream
– Upoklˆseic thc iostream: fstream, stringstream
• cin: antikeÐmeno thc istream
• cout, cerr, clog: antikeÐmena thc ostream
• istream: klˆsh gia reÔmata eisìdou (sunˆrthsh
-telest c: >>)
• ostream: klˆsh gia reÔmata exìdou (sunˆrthsh -telest c:
<<)
• iostream: klˆsh gia reÔmata eisìdou/exìdou
• Klˆsh streambuf: prosfèrei tic basikèc leitourgÐec I/O.
93

'Exodoc Metablht¸n Sthn klˆsh ostream orÐzetai o


telest c << gia na qeirÐzetai thn èxodo twn enswmatwmènwn
tÔpwn thc C++.
class ostream : public virtual ios
{
// ...
public:
basic_ostream& operator<<(const char*);
basic_ostream& operator<<(char);
basic_ostream& operator<<(short);
basic_ostream& operator<<(int);
basic_ostream& operator<<(long);
// ...
};

• Mia sunˆrthsh tou telest  << epistrèfei anaforˆ se


ostream gia na mporeÐ na efarmosteÐ ki ˆlloc << sth
sunèqeia, pˆnw sto apotèlesmˆ thc (omadopoÐhsh apì
aristerˆ proc ta dexiˆ).
• Gia nèouc tÔpouc apì to qr sth, arkeÐ o qr sthc na orÐsei
mia
ostream& operator<<(ostream& str, <new cl obj >)
94

EÐsodoc Metablht¸n
Kat’ analogÐa me thn èxodo.
Sthn klˆsh istream orÐzetai o telest c >> gia na qeirÐzetai
thn eÐsodo twn enswmatwmènwn tÔpwn thc C++.
class istream : public virtual ios
{
// ...
public:
basic_istream& operator>>(const char*);
basic_istream& operator>>(char&);
basic_istream& operator>>(short&);
basic_istream& operator>>(int&);
// ...
};

• O telest c >> diabˆzei katˆ tÔpo.


• kenì, tab, nl, cr, fd: (whitespaces) diaqwristikˆ
• Gia nèouc tÔpouc apì to qr sth, arkeÐ o qr sthc na orÐsei
mia
istream& operator>>(istream& str, <new cl obj >)
95

ShmaÐec morfopoÐhshc thc ios (èna enumeration thc


ios)
showbase/noshowbase: indicate the numeric base when printing
a num value
showpos/noshowpos: show (+) for positive values
uppercase/nouppercase: display uppercase for hex and
scientific values
showpoint/noshowpoint: show decimal point and trailing zeroes
for floating-point values
skipws/noskipws: skip whitespace on input
left/right/internal: output left/right justified /
padding in-between
scientific: use scientific notation
fixed: normal display with precision as specified or 6 (default)
dec/oct/hex: numeric base

. . . mporoÔn na sunduastoÔn bitwise


96

Qeirismìc twn shmaÐwn morfopoÐhshc


• setf sunˆrthsh-mèloc thc ios,
long setf(long<flags>);
p.q.
cout.setf(ios::hex);
cout.setf(ios::showbase);
  kalÔtera
cout.setf(ios::showbase|ios::hex);

• long unsetf(long< flags>);


• long setf(long<flags1 >, long<flags2 >); reset<
flags2 > and set<flags1 >
• long flags();: èlegqoc shmai¸n
• long flags(long <flag>);

'Allec sunart seic -mèlh thc ios


• int width(int<width>): orÐzei to eÔroc enìc pedÐou
exìdou
• int precision(int<precision>): orÐzei thn akrÐbeia
katˆ thn èxodo twn pragmatik¸n
• char fill(char<char >): orÐzei to qarakt ra pou
“gemÐzei” ta pedÐa exìdou
97

KLASEIS
• Orismìc apì to qr sth nèwn tÔpwn, h prìsbash sta
stoiqeÐa twn opoÐwn gÐnetai mèsw sugkekrimènwn
sunart sewn.
• 'Enac tÔpoc eÐnai h fusik  anaparˆstash miac ideat c
ontìthtac. p.q. o tÔpoc float me +,-,* . . . eÐnai h
anaparˆstash tou pragmatikoÔ arijmoÔ twn majhmatik¸n.
• 'Ena prìgramma pou qrhsimopoieÐ tÔpouc pou
prosomoi¸noun tic ontìthtec thc efarmog c gÐnetai
eukolìtera katanohtì.
• Diaqwrismìc twn leptomerei¸n ulopoÐhshc tou tÔpou apì
tic idiìthtec/leitourgÐec tou tÔpou pou eÐnai aparaÐthtec
gia th swst  qr sh tou.
98

Klˆseic sth C++


• H jemeli¸dhc ènnoia tou tÔpou pou orÐzetai apì to qr sth
sth C++ eÐnai aut  thc klˆshc (class).
• H prìsbash sta antikeÐmena miac klˆshc gÐnetai mèsw twn
sunart sewn-mel¸n (member functions) thc klˆshc.
(upˆrqei ki ˆllh mia dunatìthta, mèsw filik¸n
sunart sewn kai filik¸n klˆsewn, friends).
• H dhmiourgÐa antikeimènwn miac klˆshc gÐnetai mèsw
sugkekrimènwn sunart sewn pou dhl¸nontai sth klˆsh kai
lègontai sunart seic kataskeu c (constructors).
• Kat’ analogÐa, orÐzontai sunart seic katastrof c
(destructors) gia thn katastrof  twn antikeimènwn twn
klˆsewn kai thn apeleujèrwsh tou q¸rou.
• 'Ena antikeÐmeno miac klˆshc mporeÐ na dhmiourghjeÐ eÐte
san static eÐte san automatic eÐte mèsw new.
99

TÔpoi dedomènwn orismènoi apì to qr sth -


Sunart seic -mèlh

Sth C ja mporoÔsame na eÐqame, gia parˆdeigma:


struct date { int day, month, year; };
date today;
void set_date(date*, int, int, int);
// ...
Autì, sth C++, mporeÐ na grafteÐ san
struct date {
int day, month, year;
void set_date(int, int, int);
// ...
}

Se aut  thn perÐptwsh th sunˆrthsh set date thn ekfrˆsame


san sunˆrthsh-mèloc tou tÔpou date kai ennoeÐtai ìti, katˆ th
qr sh thc, efarmìzetai aparaÐthta se èna antikeÐmeno tou
tÔpou.
D lwsh sunart sewn -mel¸n enìc nèou tÔpou. P.q.
struct date {
int day, month, year;
void set(int, int, int);
void get(int*, int*, int*);
};
Kl sh sunart sewn -mel¸n gia mia metablht  tou nèou tÔpou
date today;
int d,m,y;
today.set(3,5,2004);
today.get(&d,&m,&y);
100

cout << "day " << d


<< ", month " << m
<< ", year " << y << endl ;

Orismìc sunart sewn -mel¸n


void date::set(int i, int j, int k)
{
month = i;
day = j;
year = k;
}

void date::get(int* i, int* j, int* k)


{
*i = month;
*j = day ;
*k = year;
}

PROSOQH: mia sunˆrthsh -mèloc qrhsimopoieÐ ta onìmata


ˆllwn mel¸n qwrÐc na anafèrei rhtˆ kˆpoio antikeÐmeno:
uponoeÐtai to antikeÐmeno gia to opoÐo kl jhke h sunˆrthsh
-mèloc.
101

Oloklhrwmènoc orismìc tou nèou tÔpou date,


Orismìc Sunart sewn-mel¸n tou kai Qr shc tou
#include <iostream.h>

struct date {
int day, month, year;
void set(int, int, int);
void get(int&, int&, int&);
};

main()
{
date today;
int d,m,y;
today.set(3,5,2004);
today.get(d,m,y);
cout << "day " << d
<< ", month " << m
<< ", year " << y << endl ;
}

void date::set(int i, int j, int k)


{
month = i; day = j; year = k;
}

void date::get(int& i, int& j, int& k)


{
i = month;
j = day ;
k = year;
}
102

AfaÐresh sta dedomèna - Klˆseic

Me th qr sh thc struct ìpwc kˆname prohgoÔmena, den


ekfrˆsame ìti ta antikeÐmena ja eÐnai (ˆmesa) prospelˆsima
MONO apì tic sunart seic -mèlh. An autì eÐnai to epijumhtì,
autì, sun jwc, epitugqˆnetai me th qr sh class antÐ gia
struct.

Genik  dom  klˆshc:


class< ìnoma klˆshc >
{
<dhl¸seic>

public:
<dhl¸seic>
};
'H alli¸c:
class< ìnoma klˆshc >
{
public:
<dhl¸seic>

private:
<dhl¸seic>
};
103

To parˆdeigma tou nèou tÔpou date, orismèno san klˆsh


#include <iostream.h>

class date {
private:
int day, month, year; // data members kept hidden
public:
void set(int, int, int);
void get(int&, int&, int&);
};

main()
{
date today;
int d,m,y;
today.set(3,5,2004);
today.get(d,m,y);
cout << "day " << d
<< ", month " << m
<< ", year " << y << endl ;
}

void date::set(int i, int j, int k)


{
month = i;
day = j;
year = k;
}

void date::get(int& i, int& j, int& k)


{
i = month;
j = day ;
k = year;
}
104

Oratìthta kai prospèlash sta mèlh miac klˆshc


• Ta onìmata tou idiwtikoÔ (private) mèrouc thc klˆshc
mporoÔn na qrhsimopoihjoÔn MONO apì tic sunart seic
-mèlh thc klˆshc (genikìtera, mìno apì thn embèleia thc
klˆshc).
• To dhmìsio (public) mèroc miac klˆshc apoteleÐ th diepaf 
(interface) thc klˆshc mèsw thc opoÐac ta antikeÐmena thc
klˆshc eÐnai prospelˆsima èxw apì thn klˆsh.
• ShmeÐwsh: mia struct eÐnai mia class thc opoÐac ta mèlh
(by default) eÐnai dhmìsia en¸ mia class eÐnai mia struct
thc opoÐac ta mèlh (by default) eÐnai idiwtikˆ.
• Oi sunart seic -mèlh kaj¸c kai ta mèlh dedomèna
dhl¸nontai, kaloÔntai kai orÐzontai akrib¸c ìpwc kai sth
struct.
• H prospèlash sta mèlh miac class gÐnetai ìpwc kai se
struct (me th qr sh twn telest¸n . kai ->, anˆloga an
èqoume metablht  tou tÔpou   deÐkth se metablht  tou
tÔpou)
105

OrÐzontac mia klˆsh, sun jwc milˆme gia


• ta domikˆ stoiqeÐa pou ktÐzoun to antikeÐmeno thc klˆshc
(building blocks)
• mia seirˆ apì sunart seic -mèlh pou anajètoun timèc sta
domikˆ stoiqeÐa (mutators) kai
• mia seirˆ apì sunart seic -mèlh pou anaktoÔn tic timèc
autèc (accessors)
Parˆdeigma:
class Student
{
private:
char* name; // +
int no; // | Building blocks
int year_of_studies; // +
public:
void set_name(const char*); // +
void set_no(int); // | Mutators
void set_year_of_studies(int); // +
char* get_name(); // +
int get_no(); // | Accessors
int get_year_of_studies(); // +
};

Qr sh tou tÔpou Student


main(){
Student s;
int year, no;

s.set_name("FName LName");
s.set_no(555);
s.set_year_of_studies(1);

year = s.get_year_of_studies();
no = s.get_no();
}
106

O nèoc tÔpoc Student: orismìc - qr sh - dom  arqeÐwn


progrˆmmatoc:

ArqeÐa:
• Orismìc nèou tÔpou:
– student.h: orismìc tou nèou tÔpou (arqeÐo
-epikefalÐda)
– student.cpp: orismìc twn sunart sewn -mel¸n tou
nèou tÔpou (arqeÐo k¸dika)
//File: student.h
class Student {
private:
char* name;
int no;
int year_of_studies;
public:
void set_name(const char*);
void set_no(int);
void set_year_of_studies(int);
char* get_name();
int get_no();
int get_year_of_studies();
};
//File: student.cpp
#include <string.h>
#include <iostream.h>
#include "student.h"

void Student::set_name(const char* nam)


{
name = new char[strlen(nam)+1];
strcpy(name,nam);
}

void Student::set_no(int n){


no = n;
}
107

void Student::set_year_of_studies(int y){


year_of_studies = y;
}

char* Student::get_name(){
return name;
}

int Student::get_no(){
return no;
}

int Student::get_year_of_studies(){
return year_of_studies;
}

• classtest.cpp: qr sh tou nèou tÔpou ston orismì


metablht¸n
//File: classtest.cpp
#include <iostream.h>
#include "student.h"

int main()
{
Student s;
int year, no;

s.set_name("First Last");
s.set_no(100);
s.set_year_of_studies(1);
s.set_name("NFirst Last");

year = s.get_year_of_studies();
no = s.get_no();
cout << "\nYear of studies is " << year <<
" for student with no " << no <<
" and name " << s.get_name() << endl ;
}
108

'Allec parathr seic sqetikˆ me tic klˆseic

O deÐkthc this

• Ousiastikˆ, oi sunart seic -mèlh douleÔoun san na


èqoun krummèno èna ìrisma pou anafèretai se deÐkth
sto antikeÐmeno gia to opoÐo kaloÔntai. Dhlad , gia
mia klˆsh X, o deÐkthc eÐnai X *const this (to this
upodhl¸nei to deÐkth sto antikeÐmeno gia to opoÐo
kaleÐtai h sunˆrthsh).
• H qr sh tou this èqei nìhma ìtan mia sunˆrthsh
-mèloc paÐrnei san ìrisma metablhtèc thc Ðdiac thc
klˆshc (p.q. void append(list*); gia sunènwsh
list¸n) kai/  upˆrqei anˆgkh gia prìsbash sto deÐkth
kai qeirismoÔ tou mèsa apì to s¸ma thc sunˆrthshc
kai/  epistrof c tou antikeimènou apì th sunˆrthsh.
• Se perÐptwsh pou mia sunˆrthsh -mèloc den prìkeitai
na tropopoi sei to antikeÐmeno gia to opoÐo kaleÐtai,
tìte sth d lws  thc sumperilambˆnoume th lèxh -kleidÐ
const, p.q. char* get name() const;. S’ aut n thn
perÐptwsh, o tÔpoc tou this mporeÐ na jewrhjeÐ ìti
eÐnai gia mia klˆsh X , const X *const this
109

inline sunart seic -mèlh

ProgrammatÐzontac me klˆseic, suqnˆ qrhsimopoioÔme polÔ


mikrèc sunart seic. To kìstoc kl shc miac sunˆrthshc
eÐnai megˆlo. Mia sunˆrthsh -mèloc pou orÐzetai -ki ìqi
apl¸c dhl¸netai- ston orismì miac klˆshc jewreÐtai ìti
eÐnai inline. p.q.
class Student
{
char* name;
// ...
public:
// ...
char* get_name() { return name; } // INLINE
// ...
};
110

ArqikopoÐhsh stigmiotÔpwn
• DÐnetai h dunatìthta ston programmatist  na dhl¸nei
kˆpoia(ec) sunart seic pou èqoun san stìqo na
dhmiourgoÔn kai na arqikopoioÔn antikeÐmena (dhlad ,
upˆrqei h dunatìthta tautìqronhc arqikopoÐhshc katˆ th
stigm  thc d lwshc).
• Oi sunart seic autèc lègontai sunart seic kataskeu c
(constructors) kai prosdiorÐzontai apì to ìti èqoun to Ðdio
ìnoma me thn klˆsh. p.q.
class date{
// ...
public:
date(int, int, int);
date(int, int); // this year
date(int); // this year and this month
date(); // today
// ...
};

main()
{
// ...
date day(14);
date day_month(14,3);
date today;
// ...
}

• Mia klˆsh pou den èqei sunart seic kataskeu c mporeÐ na


arqikopoi sei antikeÐmenˆ thc me anˆjesh ˆllwn
antikeimènwn thc (p.q. date d = today; arqikopoÐhsh thc
d me anˆjesh thc today). Autì isqÔei akìma kai gia
peript¸seic pou h klˆsh èqei sunart seic kataskeu c.
• GÐnetai epimèrouc anˆjesh tim¸n (bitwise copy), se
perÐptwsh pou den èqei dojeÐ kˆpoioc ˆlloc orismìc.
111

• O ˆlloc orismìc ousiastikˆ anafèretai sto na oristeÐ mia


sunˆrthsh, gia mia klˆsh X , X::X(const X&).
• Aut  eÐnai h sunˆrthsh kataskeu c antigrˆfwn (copy
constructor).
• EÐnai endiafèron na xekajaristoÔn ta parakˆtw:
1. Kataskeu  stigmiìtupou klˆshc me arqikopoÐhsh (me
paramètrouc ˆllou tÔpou) (me qr sh sunˆrthshc
kataskeu c)
2. Kataskeu  stigmiìtupou klˆshc me antigraf  (me
qr sh sunˆrthshc kataskeu c antigrˆfwn)
3. Anˆjesh stigmiotÔpwn (me uperfìrtwsh tou telest 
anˆjeshc, =)
PROSOQH: h qr sh tou telest  anˆjeshc ston orismì
metablht c klˆshc DEN eÐnai èkfrash anˆjeshc. UponoeÐ
qr sh tou copy constructor.
112

Katastrof  stigmiotÔpwn
• H antÐstrofh diadikasÐa thc kataskeu c antikeimènwn eÐnai
ekeÐnh thc katastrof c antikeimènwn.
• PolloÐ tÔpoi qreiˆzontai na oristeÐ mia sunˆrthsh
katastrof c (destructor) antikeimènwn gia na diasfalisteÐ
h orj  apeleujèrwsh tou q¸rou pou katalambˆnei èna
antikeÐmenì touc.
• Genik  morf , gia mia klˆsh X , ~X() (~: sumpl rwma)
• 'Otan ta antikeÐmena dhmiourgoÔntai mèsw new, dunamikˆ,
qreiˆzetai sunˆrthsh katastrof c pou na kaleÐtai kai na
apeleujer¸nei to q¸ro pou katèlaban.
• 'Otan èna antikeÐmeno bgaÐnei apì thn embèleia, kaleÐtai h
sunˆrthsh katastrof c thc klˆshc tou. PROSOQH: sth
C++, bgaÐnontac apì to s¸ma thc main, den stamatˆ h
ektèlesh: kaloÔntai kai oi sunart seic katastrof c ìlwn
twn antikeimènwn pou dhmiourg jhkan.
113

To parakˆtw parˆdeigma sac epitrèpei na peiramatisteÐte me tic


ektelèseic twn sunart sewn kataskeu c kai katastrof c miac
klˆshc kaj¸c kai me ton epanaorismì tou telest  anˆjeshc
san mèloc miac klˆshc. (UpenjÔmish: h qr sh tou telest 
anˆjeshc katˆ ton orismì miac metablht c tÔpou klˆshc eÐnai
isodÔnamh me qr sh tou copy constructor kai parèqetai apì th
gl¸ssa gia lìgouc sumbatìthtac me thn arqikopoÐhsh twn
enswmatwmènwn tÔpwn)
PeiramatisteÐte afair¸ntac stadiakˆ ta sqìlia. Prospaj ste
na aitiolog sete ta apotelèsmata thc ektèleshc. (UpenjÔmish:
To pèrasma paramètrwn se sunˆrthsh kaj¸c kai h epistrof 
apotelèsmatoc eÐnai antÐstoiqo me arqikopoÐhsh ki ìqi anˆjesh)
ArqeÐo -epikefalÐda student constr.h
//File: student_constr.h
class Student {
private:
char* name;
int no;
int year_of_studies;
public:
Student(const char*);
Student(const Student&);
~Student();
Student& operator=(const Student& s);
void set_name(const char*);
void set_no(int);
void set_year_of_studies(int);
char* get_name();
int get_no();
int get_year_of_studies();
};
114

ArqeÐo -k¸dika student constr.cpp


//File: student_constr.cpp
#include <string.h>
#include <iostream.h>
#include "student_constr.h"

//////////////////////////////////////////////////////////

void Student::set_name(const char* nam)


{
delete[] name;
name = new char[strlen(nam)+1];
strcpy(name,nam);
}

void Student::set_no(int n)
{no = n;}

void Student::set_year_of_studies(int y)
{year_of_studies = y;}

//////////////////////////////////////////////////////////

char* Student::get_name()
{return name;}

int Student::get_no()
{return no;}

int Student::get_year_of_studies()
{return year_of_studies;}
//////////////////////////////////////////////////////////

Student::~Student()
{
cout << "Deleting student with name " << name << endl ;
delete[] name;
}
//////////////////////////////////////////////////////////

Student::Student(const char* nam)


{
115

name = new char[strlen(nam)+1];


strcpy(name,nam);
cout << "I just constructed a student " << endl;
}

Student::Student(const Student& s)
{
// name = s.name; Careful: this is the result
// of default copy
name = new char[strlen(s.name)+1];
strcpy(name,s.name);

no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just created a student by copying ... " << endl;
}
//////////////////////////////////////////////////////////

Student& Student::operator=(const Student& s)


{

// name = s.name; Careful: this is the result


// of default assignment

if (this != &s) // Careful not to assign to itself, especially


// if some storage reclaim was made within the body
{
delete[] name;
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just performed a student ASSIGNMENT ... " << endl;
}
return *this;

}
116

Qr sh thc klˆshc Student


//File: classtest_constr.cpp
#include <iostream.h>
#include "student_constr.h"

void bla(Student s)
{ cout << "Body of the bla function" << endl;}

Student blaS(Student s)
{ cout << "Body of the blaS function" << endl;
return s;}

int main()
{
Student s("First Last");
cout << "This is the first output of the main function "
<< endl;

s.set_no(100);
s.set_year_of_studies(1);
s.set_name("NFirst Last");

int year, no;

year = s.get_year_of_studies();
no = s.get_no();
cout << "\nYear of studies is " << year <<
" for student with no " << no <<
" and name " << s.get_name() << endl ;
///////////////////////////////////////////////////////////////////////
// Student scopied(s); // Student creation with copy constructor
// Student sassgncopied = s; // Student creation EQUIVALENT TO
// // THE ABOVE
// scopied = sassgncopied; // Student assignment (to an existent
// // Student)
// bla(s);
//
// scopied = blaS(s);

cout << "Just exiting the main function ...."


<< endl << endl; }
117

PeiramatisteÐte kai gia thn perÐptwsh pou to pèrasma


paramètrwn h/kai h epistrof  sunˆrthshc gÐnetai me anaforˆ.
Antikatast ste to arqeÐo classtest constr.cpp me to arqeÐo
refclass test.cpp pou akoloujeÐ.

//File: refclass_test.cpp
#include <iostream.h>
#include "student_constr.h"

void bla(Student& s)
{
cout << "Body of the bla function" << endl;
}

Student& blaS(Student& s) // interchange with next header to experiment


// with temporaries
// Student& blaS(Student s)
{
cout << "Body of the blaS function" << endl;
return s;
}

int main()
{
Student s("First Last");
Student & rs = s;
cout << "This is the first output of the main function "
<< endl;
int year, no;

s.set_no(100);
s.set_year_of_studies(1);
s.set_name("NFirst Last");

year = s.get_year_of_studies();
no = s.get_no();
cout << "\nYear of studies is " << year <<
" for student with no " << no <<
" and name " << s.get_name() << endl ;
118

/////////////////////////////////////////////////////////////////////////////
Student scopied(s);
//
//
bla(s);
//
scopied = blaS(s);

cout << "Just exiting the main function ...."


<< endl << endl;
}
119

Proter mata thc afaÐreshc sta dedomèna:


PeiramatisteÐte me ta parakˆtw. Orismìc enìc nèou tÔpou
Time me dÔo diaforetikèc anaparastˆseic:
1. Oi ¸rec kai ta leptˆ fulˆssontai qwristˆ (arqeÐa
time1.h - time1.cc)
//File: time1.h
class Time
{
int hours;
int mins;

public:
Time() { hours = 0; mins = 0; };
~Time() {};
void set(int,int);
void print();
Time add(Time);
};

//File: time1.cc
#include <iostream.h>
#include "time1.h"

void Time::print()
{
cout << hours <<" hours and "
<< mins <<" mins " << endl;
}

void Time::set(int h, int m)


{
hours = h;
mins = m;

print();

// this->print(); // Equivalent to the above


}
120

Time Time::add(Time t)
{
Time result;
result.hours = 0;
result.mins = mins + t.mins;

if (result.mins > 60)


{
result.mins -= 60;
result.hours += 1;
}

result.hours += hours + t.hours;

return result;
}

2. O qrìnoc anaparistˆnetai mìno apì ta leptˆ (arqeÐa


time2.h - time2.cc)
//File: time2.h
class Time
{

int tmins;

public:

Time() {tmins = 0;}


~Time() {};

void set(int,int);
void print();
Time add(Time);
};
//File: time2.cc
#include <iostream.h>
#include "time2.h"

void Time::print()
{
cout << tmins / 60 <<" hours and "
<< tmins \% 60 <<" mins " << endl;
}
121

void Time::set(int h, int m)


{
tmins = h * 60 + m;

print();

// this->print();
}

Time Time::add(Time t)
{
Time result;
result.tmins = tmins + t.tmins;

return result;
}
122

Qr sh tou nèou tÔpou Time san summigoÔc (arqeÐo


timetest.cc): h qr sh eÐnai anexˆrthth apì thn
anaparˆstash kai thn ulopoÐhsh tou tÔpou.
#include<iostream.h>
//#include "time1.h"
//#include "time2.h"

int main()

{
Time t;

t.print();
t.set(2,59);

// t.hours; Not visible (even if time1.h is included)

Time tt;
tt.set(1,59);

Time ttt;
ttt = t.add(tt);

ttt.print();

return 0;
}

Kˆnontac include to antÐstoiqo arqeÐo -epikefalÐda,


qrhsimopoieÐtai apì to metaglwttist  o antÐstoiqoc orismìc
thc Time. Poioc enallaktikìc orismìc eÐnai katallhlìteroc,
exartˆtai apì thn efarmog  sthn opoÐa qrhsimopoieÐtai.
123

Parˆdeigma qr shc twn glwssik¸n dom¸n thc C++ class,


struct kai typedef.
#include<iostream.h>
#include<string.h>
//#include "time1.h"
//#include "time2.h"

typedef int FligthNoType; // just renaming:


// provisional type
// for FligthNoType,
// we may change it later

struct Flight // Flight is actually a


{ // data structure. Also no
FligthNoType FNo; // encapsulation is needed
char* DCity;
char* ACity;
Time DTime;
Time Duration;
};

int main()
{
Flight AthensParis;

AthensParis.FNo = 314;
AthensParis.DCity = "Athens";
AthensParis.ACity = "Paris";
AthensParis.DTime.set(10,30);
AthensParis.Duration.set(3,15);

Time ATime;

ATime = AthensParis.DTime.add(AthensParis.Duration);

cout << AthensParis.DCity


<< " to " << AthensParis.ACity
<< endl;
cout << "Arriving ...at " ;
ATime.print();

return 0;
}
124

EPANAQRHSIMOPOIHSH (reusability)
• mèsw sÔnjeshc (composition) has a
• mèsw klhronomikìthtac (inheritance) is a
125

SÔnjesh
• Mia klˆsh èqei san mèlh antikeÐmena ˆllhc klˆshc.
• DhmiourgÐa antikeimènwn: Pr¸ta dhmiourgoÔntai ta
antikeÐmena pou eÐnai mèlh thc klˆshc (me th seirˆ pou
dhl¸nontai ston orismì thc klˆshc ki ìqi me th seirˆ pou
emfanÐzontai sth sunˆrthsh kataskeu c thc klˆshc) ki
èpeita dhmiourgeÐtai to antikeÐmeno thc klˆshc.
• Katastrof  antikeimènwn: AkoloujeÐtai h antÐstrofh
seirˆ apì ekeÐnh thc dhmiourgÐac, dhlad , pr¸ta ekteleÐtai
to s¸ma thc sunˆrthshc katastrof c thc klˆshc kai metˆ
ekeÐnec twn mel¸n thc (me thn antÐstrofh seirˆ thc
d lwshc).
126

Parˆdeigma gia:
• ton orismì pollapl¸n sunart sewn kataskeu c (me qr sh
default tim¸n sta orÐsmata)
• th qr sh initializer list gia non -class mèlh -dedomèna
(isodÔnamo me anˆjesh sto s¸ma thc sunˆrthshc
kataskeu c) (ShmeÐwsh: aut  h suntaktik  dunatìthta
parèqetai gia lìgouc sumbatìthtac me ta class mèlh
-dedomèna ìpou sthn perÐptwsh aut , ètsi pernˆme
paramètrouc stic sunart seic kataskeu c touc)
• ton orismì klˆshc me mèlh -dedomèna pou an koun se ˆllec
klˆseic
• thn kl sh (non -trivial synthesized) sunart sewn
kataskeu c/katastrof c gia ta antikeÐmena thc sÔnjethc
klˆshc
PeiramatisteÐte bgˆzontac ta sqìlia twn orism¸n twn
metablht¸n sto s¸ma thc main tou akìloujou progrˆmmatoc.
127

#include <iostream.h>
/////////////////////////////////////////////////////////////////////
class Date {

int day;
int month;
int year;

public:
Date(int d = 1, int m = 1, int y = 2004)
// : day(d), month(m), year(y) // non-class types,
// i.e. intitializer list
// alternative to assignment
// in the body
{
day = d; month = m; year = y;

cout << "I just created a Date with value: "


<< day << ’ ’ << month << ’ ’ << year << endl;
}

~Date()
{
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl;
}

void print()
{
cout << day << ’ ’ << month << ’ ’ << year
<< endl;
}

};
/////////////////////////////////////////////////////////////////////
class Time {

int hours;
int mins;

public:

Time(int h = 0, int m = 0 )
// : hours(h); mins(m)
128

{
hours = h; mins = m;
cout << "I just created a Time with value: "
<< hours << ’ ’ << mins << endl;
}

~Time()
{ cout << ’\n’ << "I am destroying a Time with value: "
<< hours << ’ ’ << mins << endl; }

void print() {
cout << hours <<" hours and "<< mins <<" mins "
<< endl;}

};
/////////////////////////////////////////////////////////////////////
class DetailedDate{

Date date;
Time time;

public:
DetailedDate()
// Default constructor is synthesized, using the default constructors
// of the data members.
{ cout << "DetailedDate was just created with value:"
<< ’\n’ << endl;
// NO VISIBILITY in private part
// cout << date.day << ’ ’ << date.month << ’ ’
// << date.year << endl;
// cout << time.hours <<" hours and "<< time.mins
// <<" mins " << endl;
date.print();
time.print();
}

DetailedDate(int d, int mo, int y, int h, int mi):


date(d,mo,y), time(h,mi)
// Initializer list is required to pass the values to the constructors
// of data members.
{ cout << "DetailedDate was just created with value:"
<< ’\n’ << endl;

date.print();
129

time.print();
}

~DetailedDate()
{
cout << ’\n’
<< "I am destroying a DetailedDate with value: "
<< endl;
date.print();
time.print();
}
};
/////////////////////////////////////////////////////////////////////
int main()
{

// Date d1;
// Date d2(3);
// Date d3(3,4);
// Date d4(3,4,2005);

// Time t1;
// Time t2(35);
// Time t3(2,35);

// dd1 and dd2 are instances/objects of DetailedDate

DetailedDate dd1;
// DetailedDate dd2(25,10,2005,3,45);

return 0;
}
130

Parˆdeigma: Mèlh-dedomèna pou eÐnai deÐktec se antikeÐmena


klˆsewn:
• Problhmatik  antimet¸pish:
1. problhmatik  arqikopoÐhsh (mh asfal c dèsmeush kai
arqikopoÐhsh)
2. kak  prospèlash mèsw deikt¸n
#include <iostream.h>
/////////////////////////////////////////////////////////////////////
class Date {

int day;
int month;
int year;

public:
Date(int d = 1, int m = 1, int y = 2004)
{
day = d; month = m; year = y;

cout << "I just created a Date with value: "


<< day << ’ ’ << month << ’ ’ << year << endl; }

~Date() {
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl; }

void print() {
cout << day << ’ ’ << month << ’ ’ << year << endl;}
};
/////////////////////////////////////////////////////////////////////
class Time {

int hours;
int mins;

public:
Time(int h = 0, int m = 0 )
{
hours = h; mins = m;
cout << "I just created a Time with value: "
131

<< hours << ’ ’ << mins << endl;}

~Time() {
cout << ’\n’ << "I am destroying a Time with value: "
<< hours << ’ ’ << mins << endl; }

void print() {
cout << hours <<" hours and "<< mins <<" mins "
<< endl;}

};
/////////////////////////////////////////////////////////////////////
class DetailedDate{

Date* date;
Time* time;

public:
DetailedDate()
{ cout << "DetailedDate was just created with value:"
<< ’\n’ << endl;
// CAREFUL: no space has been allocated or intialized
// for Date and Time

this->date->print(); // error
this->time->print(); // error
}

~DetailedDate()
{
cout << ’\n’
<< "I am destroying a DetailedDate with value: "
<< endl;
date->print();
time->print();
}
};
/////////////////////////////////////////////////////////////////////
int main()
{
DetailedDate dd1;

return 0;
}
132

• Oloklhrwmènh arqikopoÐhsh/apodèsmeush mn mhc:


peiramatisteÐte bgˆzontac ta sqìlia apì touc orismoÔc
twn metablht¸n thc main.
#include <iostream.h>
/////////////////////////////////////////////////////////////////////
class Date {

int day;
int month;
int year;

public:
Date(int d = 1, int m = 1, int y = 2004)
{
day = d; month = m; year = y;

cout << "I just created a Date with value: "


<< day << ’ ’ << month << ’ ’ << year << endl;

~Date() {
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl;
}

void print() {
cout << day << ’ ’ << month << ’ ’ << year << endl;}

};
/////////////////////////////////////////////////////////////////////
class Time {

int hours;
int mins;

public:
Time(int h = 0, int m = 0 )
{
hours = h; mins = m;
cout << "I just created a Time with value: "
<< hours << ’ ’ << mins << endl;}
133

~Time() {
cout << ’\n’ << "I am destroying a Time with value: "
<< hours << ’ ’ << mins << endl; }

void print() {
cout << hours <<" hours and "<< mins <<" mins "
<< endl;}
};
/////////////////////////////////////////////////////////////////////
class DetailedPDate{

Date* date;
Time* time;

public:
DetailedPDate()
{ cout << "DetailedPDate was just created with value:"
<< ’\n’ << endl;

date = new Date;


time = new Time;

date->print(); // actually this->date->print()


time->print();
}

DetailedPDate(int d, int mo, int y, int h, int mi)


{
cout << "DetailedPDate was just created with value:"
<< ’\n’ << endl;

date = new Date(d,mo,y);


time = new Time(h,mi);

date->print();
time->print();
}
134

~DetailedPDate()
{
cout << ’\n’
<< "I am destroying a DetailedPDate with value: "
<< endl;

date->print();
time->print();

delete date;
delete time;
}
};
/////////////////////////////////////////////////////////////////////
int main()
{

// DetailedPDate dd1;
// DetailedPDate dd2(25,10,2005,3,45);

return 0;
}
135

KLHRONOMIKOTHTA (inheritance)
VEHICLE:
(move(), position(), wheels())

/ | \
/ | \
/ | \
+ + +

CAR: BICYCLE: MOTORBIKE:


(4_wheels(), (2_wheels(), (2_wheels(),
engine()) no_engine()) engine())

/ | \ \
/ | \ \
+ | \ +
| \
CABRIO: | \ 4_WHEEL_DRIVE:
(no_roof()) | \ (drive_in_4_wheels())
| +
|
| LIMOUZINE:
+ (no_back_door())

HATCHBACK:

• 'Ena “ìqhma” èqei kˆpoia “jèsh” apì thn opoÐa mporeÐ na


“metakinhjeД me qr sh “troq¸n”.
• 'Ena “autokÐnhto” eÐnai èna “ìqhma” me “tèsseric troqoÔc”
kai “mhqan ”.
• 'Ena “cabrio” eÐnai èna “autokÐnhto” pou “den èqei orof ”.
• ...
136

• Pio genikeumènec ontìthtec kai exeidikeÔseic touc


• Diabˆzoume to parapˆnw sq ma apì pˆnw proc ta kˆtw.
Sqediˆzoume anˆpoda: BrÐskoume koinˆ qarakthristikˆ
stic ontìthtec kai ftiˆqnoume nèec, pio genikeumènec,
ontìthtec me autˆ.
• OrologÐa:
GenikeÔseic: Basik  klˆsh (base class), uperklˆsh
(superclass)
ExeidikeÔseic: Paragìmenh klˆsh (derived class),
upoklˆsh (subclass)
• 'Allo z thma sthn klhronomikìthta: pollapl 
klhronomikìthta (multiple inheritance)
137

Klhronomikìthta sth C++


• Nèec klˆseic mporoÔn na oristoÔn apì  dh upˆrqousec
enswmat¸nontac ta qarakthristikˆ kai th sumperiforˆ
touc   epanaorÐzontˆc ta ìpou eÐnai aparaÐthto.
• Mia paragìmenh klˆsh mporeÐ na prosjèsei mèlh -dedomèna
kai sunart seic -mèlh epauxˆnontac ton orismì thc
(exeidikeÔontac ìmwc ta stoiqeÐa thc).
• O telest c epÐlushc embèleiac mporeÐ na qrhsimopoihjeÐ
gia na qrhsimopoihjeÐ h ekdoq  pou orÐzetai se mia basik 
klˆsh antÐ gia thn epanaorisjeÐsa sthn paragìmenh.
• Uperfìrtwsh antÐ gia katˆrghsh sunart sewn -mel¸n thc
basik c klˆshc me qr sh using (p.q. using
BaseClass::fname).
138

Parˆdeigma: 'Enac “wromÐsjioc ergazìmenoc” san


upoperÐptwsh “ergazomènou”
Orismìc twn klˆsewn:

class Employee
{
public:
Employee(const char*, const char*);
void print() const;
~Employee();

private:
char* firstname;
char* lastname;
};

class HourlyWorker : public Employee


{
public:
HourlyWorker(const char*, const char*,
double, double);
double getPay() const;
void print() const;

private:
double wage;
double hours;
};
139

Orismìc twn sunart sewn -mel¸n thc HourlyWorker:

HourlyWorker::HourlyWorker(const char* first,


const char* last,
double initHours,
double initWage)
: Employee(first,last)
{
hours = initHours;
wage = initWage;
}

double HourlyWorker::getPay() const


{ return wage * hours; }

void HourlyWorker::print() const


{
Employee::print();
cout << "Payment:" << getPay() << endl;
}

Qr sh thc HourlyWorker:

main()
{
HourlyWorker hw("FN", "LN", 0.0, 100.0);

hw.print();
}
140

DiabajmÐseic ston èlegqo thc prìsbashc sta mèlh


miac klˆshc
'Ena mèloc miac klˆshc mporeÐ na eÐnai:
private: to ìnomˆ tou mporeÐ na qrhsimopoihjeÐ mìno apì tic
sunart seic -mèlh thc klˆshc kai filikèc sunart seic kai
filikèc klˆseic thc klˆshc.
protected: to ìnomˆ tou mporeÐ na qrhsimopoihjeÐ apì tic
sunart seic -mèlh thc klˆshc kai filikèc sunart seic kai
filikèc klˆseic thc klˆshc kaj¸c kai apì sunart seic
-mèlh paragìmenwn klˆsewn kai filikèc sunart seic kai
filikèc klˆseic paragìmenwn klˆsewn.
public: to ìnomˆ tou mporeÐ na qrhsimopoihjeÐ apì
opoiad pote sunˆrthsh.
----------------- +
| | |
| PUBLIC | | PUBLIC PART
+---------------+ +
| / PROTECTED / | |
+---------------+ | PRIVATE PART
|////PRIVATE////| |
|///////////////| |
----------------- +
141

Zht mata proc problhmatismì sthn klhronomikìthta

Anaparˆstash antikeimènwn thc paragìmenhc klˆshc:


ktÐzontai apì th sunènwsh twn mel¸n -dedomènwn thc
basik c klˆshc kai twn dik¸n thc.
Jèmata embèleiac:

• P¸c (mèsw poiwn onomˆtwn) qeirizìmaste ta


antikeÐmena thc paragìmenhc klˆshc apì ton upìloipo
k¸dika;
Sthn perÐptwsh thc is -a klhronomikìthtac (public
inheritance), pèra apì ta onìmata pou eÐnai dhlwmèna
sto dhmìsio tm ma thc paragìmenhc klˆshc, mporoÔme
na qrhsimopoi soume kai kˆje ìnoma pou eÐnai sto
dhmìsio tm ma thc basik c klˆshc. Sthn perÐptwsh pou
mia sunˆrthsh -mèloc èqei epanaoristeÐ sthn
paragìmenh, o orismìc pou upˆrqei sth basik  den eÐnai
oratìc (ektìc eˆn èqei dhlwjeÐ rhtˆ to antÐjeto mèsw
using)
• P¸c (mèsw poiwn onomˆtwn) qeirizìmaste ta
antikeÐmena thc paragìmenhc klˆshc apì to peribˆllon
thc klˆshc aut c; (p.q. sta s¸mata twn orism¸n twn
sunart sewn -mel¸n thc paragìmenhc klˆshc)
'Oson aforˆ klhronomoÔmena onìmata apì th basik 
klˆsh, mporoÔme na qrhsimopoi soume ta onìmata pou
eÐnai dhlwmèna eÐte sto public eÐte sto protected
tm ma thc.
142

• P¸c (mèsw poi¸n onomˆtwn) qeirizìmaste ta


antikeÐmena thc basik c klˆshc apì to peribˆllon thc
paragìmenhc;
'Opwc akrib¸c ja ta qeirizìmastan apì opoiod pote
ˆllo mèroc tou k¸dika, dhlad  mèsw tou dhmìsiou
tm matìc touc.
ArqikopoÐhsh - katastrof  twn antikeimènwn thc
paragìmenhc klˆshc:
• 'Otan dhmiourgeÐtai èna antikeÐmeno miac paragìmenhc
klˆshc, mia sunˆrthsh kataskeu c thc basik c klˆshc
prèpei na klhjeÐ gia na arqikopoi sei ekeÐna ta mèlh tou
stigmiotÔpou pou proèrqontai apì th basik  klˆsh.
• Stic sunart seic kataskeu c thc paragìmenhc klˆshc
prèpei na prosdiorÐzetai h sunˆrthsh kataskeu c thc
basik c pou eÐnai na qrhsimopoihjeÐ kai na perastoÔn oi
timèc sta orÐsmatˆ thc (autì gÐnetai me thc qr sh
initializer list). Diaforetikˆ kaleÐtai h default
sunˆrthsh kataskeu c thc basik c klˆshc.
• Oi sunart seic kataskeu c de klhronomoÔntai.
• Katˆ thn kataskeu  enìc antikeimènou, pr¸ta kaleÐtai
h sunˆrthsh kataskeu c thc basik c klˆshc kai metˆ
thc paragìmenhc thc.
• Katˆ thn katastrof  h seirˆ eÐnai anˆpoda.
Antigraf  (ArqikopoÐhsh mèsw antigraf c - anˆjesh metaxÔ
antikeimènwn thc paragìmenhc klˆshc): me seirˆ antÐstoiqh
me th seirˆ kl shc twn sunart sewn kataskeu c, gÐnetai
bitwise copy eÐte kaloÔntai oi (epana)orismènec
sunart seic apì to qr sth an upˆrqoun.
143

Klhronìmhsh klhronomiˆc: Ti klhronomeÐtai stouc


apogìnouc miac paragìmenhc klˆshc apì autˆ pou
klhronìmhse apì th basik  thc; (bl. dhl¸seic
klhronomikìthtac).
Ta parapˆnw isqÔoun anadromikˆ gia kˆje bˆjoc ierarqÐac.
144

Seirˆ kataskeu c - katastrof c: genik  morf 


Kataskeu :
bmcs
bc
dmcs
dc
Katastrof :
dd
dmds
bd
bmds

'Opou:
bmcs: constructors of base class data members
(me th seirˆ pou emfanÐzontai ston orismì
thc klˆshc)
bc: constructor of base class
dmcs: constructors of derived class data members
(me th seirˆ pou emfanÐzontai ston orismì
thc klˆshc)
dc: constructor of derived class
dd: destructor of derived class
dmds: destructors of derived class data members
(me thn antÐstrofh seirˆ pou emfanÐzontai
ston orismì thc klˆshc)
bd: destructor of base class
bmds: destructors of base class data members
(me thn antÐstrofh seirˆ pou emfanÐzontai
ston orismì thc klˆshc)
145

PeiramatisteÐte se jèmata oratìthtac kai anaparˆstashc me


to parakˆtw:
//: C14:Inheritance.cpp + Useful.h
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Simple inheritance
#include <iostream>
using namespace std;
class X {
int i;
public:
X() { i = 0; }
void set(int ii) { i = ii; }
int read() const { return i; }
int permute() { return i = i * 47; }
};

class Y : public X {
int i; // Different from X’s i
public:
Y() { i = 0; }
int change() {
i = permute(); // Different name call
return i; }
void set(int ii) {
i = ii;
X::set(ii); } // Same-name function call
};

int main() {
cout << "sizeof(X) = " << sizeof(X) << endl;
cout << "sizeof(Y) = "
<< sizeof(Y) << endl;
Y D;
D.change();
// X function interface comes through:
D.read();
D.permute();
// Redefined functions hide base versions:
D.set(12);
} ///:~
146

'Ena aplì parˆdeigma klhronomikìthtac: “Metaptuqiakìc


Foitht c” san upoklˆsh tou “Foitht ” thc selÐdac 113.
PeiramatisteÐte me th sumperiforˆ twn sunart sewn
kataskeu c, bgˆzontac ta sqìlia apì th sunˆrthsh main.
#include <iostream.h>
#include "/home/users/cpp/public_html/mathima14/student_constr.h"
/////////////////////////////////////////////////////////////////////
class PGStudent : public Student {

int gyear; // Graduation year

public :
PGStudent(const char* nam, int gy=0) : Student(nam), gyear(gy)
{ cout << "The Graduation year was :" << gyear
<< endl; }

int get_year() { return gyear; }


};

main()
{
PGStudent pgs1("FN1");

// PGStudent pgs2("FN2",2004);
// PGStudent pgs3(pgs2); // copy constructor invoked:
// - copy constructor of Student is used
// to copy the Student subobject
// - bitwise copy for the rest

cout << "Printing from Main:" << pgs1.get_year() << endl;


// cout << "Printing from Main:" << pgs2.get_year() << endl;
// cout << "Printing from Main:" << pgs3.get_year() << endl;

// Inherited functions:
pgs1.set_no(123);
cout << pgs1.get_no() << endl;
}
147

Parˆdeigma (sunèqeia): TropopoÐhsh tou “MetaptuqiakoÔ


Foitht ” ¸ste na peiramatisteÐte me paragìmenh klˆsh pou
èqei mèlh dedomèna pou an koun se klˆsh (kataskeu 
-katastrof , oratìthta).
#include <iostream.h>
#include "/home/users/cpp/public_html/mathima14/student_constr.h"

class Date {
int day;
int month;
int year;
public:
Date(int d = 1, int m = 1, int y = 2004)
{
day = d; month = m; year = y;

cout << "I just created a Date with value: "


<< day << ’ ’ << month << ’ ’ << year << endl;
}

~Date() {
cout << ’\n’ << "I am destroying a Date with value: "
<< day << ’ ’ << month << ’ ’ << year << endl;
}

void print() {
cout << day << ’ ’ << month << ’ ’ << year << endl;}

};

/////////////////////////////////////////////////////////////////////
class PGStudent : public Student {

Date gdate; // The graduation date

public :
PGStudent(const char* nam) : Student(nam) {}
148

PGStudent(const char* nam, int gd, int gm)


: Student(nam), gdate(gd,gm)
{ cout << "The Graduation date was :" << endl;
this -> gdate.print(); }

Date get_date() { return gdate; }


};

main()
{
PGStudent pgs1("FN");
PGStudent pgs2(pgs1);

PGStudent pgs3("FN", 22, 5);


pgs3.get_date().print(); // Careful:
// invoces copy-contructor and
// destructor of Date for the
// temporary return object of get_date
}
149

Klhronomikìthta - SÔnjesh - Pèrasma paramètrwn -


Epistrof  tim c: Kataskeu  - katastrof . Aitiolog ste ta
apotelèsmata thc ektèleshc tou parakˆtw progrˆmmatoc.
#include <iostream.h>

class A1 {
public:
A1() { cout << "constructing an A1" << endl; };
A1(int i) { cout << "constructing an A1 with :"
<< i << endl; };
~A1() {cout << "destroying an A1" << endl; }; };

class A2 {
public:
A2() { cout << "constructing an A2" << endl; };
A2(int i) { cout << "constructing an A2 with :"
<< i << endl; };
~A2() {cout << "destroying an A2" << endl; }; };

class B1 {
public:
B1() { cout << "constructing a B1" << endl; };
~B1() {cout << "destroying a B1" << endl; }; };

class A {
A1 a1;
A2 a2;
public:
A() { cout << "constructing an A" << endl; };
A(int i, int j) : a2(i), a1(j)
{ cout << "constructing an A" << endl; };
~A() {cout << "destroying an A" << endl; }; };

class B : public A {
B1 b1;
public:
B() { cout << "constructing a B" << endl; };
B(int i, int j) : A(i,j)
{ cout << "constructing a B" << endl; };
~B() {cout << "destroying a B" << endl; }; };

/////////////////////////////////////////////////////////////////////
150

void bloo(B* b)
{ cout << "Printing in bloo" << endl; }

void bla(B b)
{ cout << "Printing in bla" << endl;
bloo(&b); }

////////////////////////////////////////////////////////////////////
main()
{
B object1;
B object2(5,15);
cout << "First printing in main " << endl;

bla(object1);

bloo(&object2);

cout << "Last printing in main " << endl;


}

Al jeia, ti na shmaÐnei ken  klˆsh; Ektelèste to parakˆtw:


#include <iostream.h>

class A {};

main()
{
A a;
cout << sizeof(a) << endl;

A b;
cout << &a << ’\n’ << &b << endl; // different addresses
}
151

DeÐktec se antikeÐmena ierarqÐac klˆsewn


• Den epitrèpetai h anˆjesh stigmiotÔpou (klp...) thc
basik c klˆshc se stigmiìtupo (klp...) thc paragìmenhc
klˆshc diìti paramènoun mh orismèna ta upìloipa mèlh thc
paragìmenhc klˆshc.
• Autì mporeÐ na parakamfjeÐ eÐte epanaorÐzontac ton
telest  anˆjeshc eÐte/kai orÐzontac sunˆrthsh
metatrop c.
• PROSOQH : H qr sh deikt¸n sth basik  klˆsh (èstw ki
an se autìn èqei anatejeÐ ènac deÐkthc se paragìmenh
klˆsh) parapèmpei sth prìsbash twn sunart sewn-mel¸n
thc basik c klˆshc. Autì, ìmwc, pollèc forèc den eÐnai
epijumhtì (⇒ qr sh sunart sewn virtual).
• Me rhtì cast mporoÔme na metatrèyoume ènan deÐkth se
basik  klˆsh se deÐkth se paragìmenh. Tìte mporoÔme na
tou kˆnoume dereference mìno ìtan deÐqnei prˆgmati se èna
antikeÐmeno thc paragìmenhc klˆshc.
152

TropopoÐhsh tou “MetaptuqiakoÔ Foitht ” ¸ste na


peiramatisteÐte me anajèseic anˆmesa se (deÐktec se)
antikeÐmena klˆsewn diaforetikoÔ epipèdou miac ierarqÐac.
Bgˆlete èna -èna ta sqìlia apì tic anajèseic thc sunˆrthshc
main. (DieukrÐnish: to tm ma VARIOUS anafèretai sth sumperiforˆ
sunart sewn kataskeu c -katastrof c memonwmènhc klˆshc ki ìqi
ierarqÐac. Apl¸c, den eÐqe suzhthjeÐ nwrÐtera)
#include <iostream.h>
#include "/home/users/cpp/public_html/mathima14/student_constr.h"
/////////////////////////////////////////////////////////////////////
class PGStudent : public Student {

int gyear;
char* first_degree; // We also include the
// first degree of PGStudent

public :
PGStudent(const char* nam, const char* fd, int gy=0)
: Student(nam), gyear(gy)
{
first_degree = new char[strlen(fd)+1];
strcpy(first_degree,fd);
cout << "I just constructed a PGstudent " << endl; }

~PGStudent()
{
cout << "Deleting postgraduate student with name "
<< get_name() << endl ;
delete[] first_degree;
}

int get_year() { return gyear; }

// Many member functions are missing but are not required


// for testing the functionality of copying
};

main()
{
PGStudent pgs("FN1","FDEGR");
153

cout << "Printing from Main:" << endl;

//////////////////////////////////////////////////////
// VARIOUS:
//////////////////////////////////////////////////////

// Pointer to Student:
// Student* ps = new Student("TheNew");
// delete ps; // otherwise the destructor of Student is not called

// Array of Student:
// Student ss[100]; // Problem: no default constructor is
// provided for Student
// Student* pss = new Student[100]; // Same as above

///////////////////////////////////////////////////////

Student s("FirstLast");

Student* ps;
PGStudent* ppgs;

// pgs = s; // error
// s = pgs; // Student redefinition of operator = is called

// ppgs = ps; // error


// ps = ppgs; // ok
}
154

Polumorfismìc kai sunart seic virtual


• Mac bohjoÔn na sqediˆzoume kai na ulopoioÔme sust mata
pou eÐnai eÔkola epektˆsima.
• Mia lÔsh sthn prìsbash sto swstì orismì sunˆrthshc
-mèlouc an èqoume deÐktec se uperklˆsh:
– qr sh pedÐou tÔpou sthn uperklˆsh kai
– periptwsiologÐa stic sunart seic gia ìlec tic timèc twn
pedÐwn tÔpou
• H lÔsh sth C++: qr sh sunart sewn virtual.
• H d lwsh miac sunˆrthshc wc virtual sth basik  klˆsh
epitrèpei na epanaorÐzoume th sunˆrthsh stic paragìmenec
klˆseic kai na epitugqˆnoume thn prìsbash sth “swst ”
sunˆrthsh (orismì) sthn kˆje perÐptwsh.
• Parˆdeigma:
virtual void draw() const;
virtual void draw() const = 0; ← pure virtual
• 'Apax kai mia sunˆrthsh dhlwjeÐ virtual, paramènei
virtual gia ìlh thn ierarqÐa.
• MporeÐ kai na mhn epanaorÐzetai se kˆpoia paragìmenh
klˆsh.
• 'Otan h kl sh se mia sunˆrthsh virtual gÐnetai mèsw tou
onìmatoc tou antikeimènou kai tou telest  ., tìte h
anaforˆ epilÔetai se fˆsh metagl¸ttishc kai h sunˆrthsh
(orismìc) pou kaleÐtai eÐnai aut  pou orÐzetai ( 
klhronomeÐtai) sthn klˆsh tou antikeimènou.
• De mporoÔme na èqoume virtual sunart seic kataskeu c
155

antikeimènwn (mporoÔme na èqoume virtual sunart seic


katastrof c).
• STL: de qrhsimopoioÔn virtual sunart seic.
• 'Otan mia klˆsh èqei sunart seic virtual apoktˆ, apì to
metaglwttist , ènan “pÐnaka sunart sewn virtual” kai ta
antikeÐmenˆ thc apoktoÔn èna deÐkth ston pÐnaka autì.
156

'Ena aplì parˆdeigma qr shc sunart sewn virtual.


SugkrÐnete ta apotelèsmata thc ektèleshc twn parakˆtw dÔo
programmˆtwn.
qwrÐc qr sh sunart sewn virtual:
//: C15:Instrument2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Inheritance & upcasting
#include <iostream>
using namespace std;
enum note { middleC, Csharp, Eflat }; // Etc.

class Instrument {
public:
void play(note) const {
cout << "Instrument::play" << endl;
}
};
// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument {
public:
// Redefine interface function:
void play(note) const {
cout << "Wind::play" << endl;
}
};

void tune(Instrument& i) {
// ...
i.play(middleC);
}

int main() {
Wind flute;
tune(flute); // Upcasting
} ///:~
157

me qr sh sunart sewn virtual:


//: C15:Instrument3.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Late binding with the virtual keyword
#include <iostream>
using namespace std;
enum note { middleC, Csharp, Cflat }; // Etc.

class Instrument {
public:
virtual void play(note) const {
cout << "Instrument::play" << endl;
}
};
// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument {
public:
// Override interface function:
void play(note) const {
cout << "Wind::play" << endl;
}
};

void tune(Instrument& i) {
// ...
i.play(middleC);
}

int main() {
Wind flute;
tune(flute); // Upcasting
} ///:~
158

Ac jumhjoÔme ton “Metaptuqiakì Foitht ” thc selÐdac 152.


#include <iostream.h>
#include "/home/users/cpp/public_html/mathima14/student_constr.h"
/////////////////////////////////////////////////////////////////////
class PGStudent : public Student {
int gyear;
char* first_degree;

public :
PGStudent(const char* nam, const char* fd, int gy=0)
: Student(nam), gyear(gy)
{
first_degree = new char[strlen(fd)+1];
strcpy(first_degree,fd);
cout << "I just constructed a PGstudent " << endl; }

~PGStudent()
{ cout << "Deleting postgraduate student with name "
<< get_name() << endl ;
delete[] first_degree;
}

int get_year() { return gyear; }


};

main()
{
PGStudent pgs1("FN1","FDEGR");

cout << "Printing from Main:" << pgs1.get_year() << endl;

// Inherited functions:
pgs1.set_no(123);
cout << pgs1.get_no() << endl;
}
159

Ac anajewr soume t¸ra ton orismì thc klˆshc Student thc


selÐdac 113 prosjètontac kai mia sunˆrthsh print.
student constr.h:

class Student {
private:
char* name;
int no;
int year_of_studies;
public:
Student(const char*);
Student(const Student&);
// ~Student();
virtual ~Student();

Student& operator=(const Student& s);

void set_name(const char*);


void set_no(int);
void set_year_of_studies(int);

char* get_name();
int get_no();
int get_year_of_studies();

// void print();
virtual void print();
};

student constr.cc:

#include <string.h>
#include <iostream.h>
#include "student_constr.h"

void Student::print()
{
cout << "Student’s name is: " << name << endl;
}
160

//////////////////////////////////////////////////////////
void Student::set_name(const char* nam)
{
delete[] name;
name = new char[strlen(nam)+1];
strcpy(name,nam);
}

void Student::set_no(int n)
{
no = n;
}

void Student::set_year_of_studies(int y)
{
year_of_studies = y;
}
//////////////////////////////////////////////////////////
char* Student::get_name()
{
return name;
}

int Student::get_no()
{
return no;
}

int Student::get_year_of_studies()
{
return year_of_studies;
}
//////////////////////////////////////////////////////////
Student::~Student()
{
cout << "Deleting student with name " << name
<< endl ;
delete[] name;
}
//////////////////////////////////////////////////////////
Student::Student(const char* nam)
{
name = new char[strlen(nam)+1];
strcpy(name,nam);
161

cout << "I just constructed a student " << endl;


}

Student::Student(const Student& s)
{
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just created a student by copying ... "
<< endl;
}
//////////////////////////////////////////////////////////
Student& Student::operator=(const Student& s)
{
if (this != &s) // Careful not to assign to itself
{
delete[] name;
name = new char[strlen(s.name)+1];
strcpy(name,s.name);
no = s.no;
year_of_studies = s.year_of_studies;
cout << "I just performed a student ASSIGNMENT ... "
<< endl;
}
return *this;
}
162

Ac epaux soume ton orismì thc klˆshc PGStudent ¸ste na


epanorÐzei th sunˆrthsh -mèloc print. PeiramatisteÐte
bgˆzontac ta sqìlia apì th sunˆrthsh main tou parakˆtw
progrˆmmatoc, bgˆzontac tautìqrona kai ta sqìlia apì ton
orismì thc klˆshc Student. Se kˆje perÐptwsh, o destructor
thc klˆshc Student prèpei na èqei dhlwjeÐ virtual gia na
èqoume swst  apodèsmeush katˆ thn katastrof  tou deÐkth se
Student pou sthn pragmatikìthta deÐqnei se antikeÐmeno thc
PGStudent.
#include <iostream.h>
#include "student_constr.h"
/////////////////////////////////////////////////////////////////////
class PGStudent : public Student {

int gyear;
char* first_degree;

public :

PGStudent(const char* nam, const char* fd, int gy=0)


: Student(nam), gyear(gy)
{
first_degree = new char[strlen(fd)+1];
strcpy(first_degree,fd);
cout << "I just constructed a PGstudent " << endl; }

~PGStudent()
{
cout << "Deleting postgraduate student with name "
<< get_name() << endl ;
delete[] first_degree;
}

int get_year() { return gyear; }

void print()
{ Student::print();
cout << "First degree is: " << first_degree << endl; }
};
163

main()
{
// PGStudent pgs("FN1","FDEGR");

cout << "Printing from Main:" << endl;

// Student s("FirstLast");

// s.print();
// pgs.print();
// pgs.Student::print();

/////////////////////////////////////////////
// Student* ps=&s;
// PGStudent* ppgs=&pgs;

// ps->print();
// ppgs->print();

/////////////////////////////////////////////
// Student* ss[2];

// ss[0] = &s;
// ss[1] = &pgs;

// ss[0]->print();
// ss[1]->print();

// ss[0] = new Student("TestSt");


// ss[1] = new PGStudent("TestPSt","FDeg");

// delete ss[0];
// delete ss[1];
/////////////////////////////////////////////

// Student* p1 = new Student("TestSt");


// Student* p2 = new PGStudent("TestPSt","FDeg");

// delete p1;
// delete p2; }
164

Afhrhmènec klˆseic (Abstract base classes) 'Otan mia klˆsh


èqei mia (  perissìterec) pure virtual sunart seic, tìte:
• den mporoÔme na èqoume antikeÐmena aut¸n twn klˆsewn
• autèc oi klˆseic lègontai Afhrhmènec Klˆseic (Abstract
Base Classes)
• autèc oi klˆseic qrhsimeÔoun mìno gia klhronomikìthta
upograf¸n (signatures) kai ulopoÐhshc.
• Parˆdeigma
Shape <--- ABC
|
|
+
TwoDimShape <--- ABC
/ | \
/ | \
+ + +
Square Circle Triangle

• An mia paragìmenh klˆsh den orÐzei mia pure virtual


sunˆrthsh, tìte kai h klˆsh aut  eÐnai afhrhmènh.
• Parìlo pou den mporoÔme na orÐsoume antikeÐmena miac
afhrhmènhc klˆshc mporoÔme na orÐsoume deÐktec se
afhrhmènec klˆseic kai anaforèc se afhrhmènec klˆseic
gia na petÔqoume polumorfikì qeirismì se antikeÐmena
paragìmenwn klˆsewn.
165

• H klˆsh Shape:
class Shape
{
// ...
virtual void print() const = 0;
// ...
};
166

Pollapl  Klhronomikìthta
Employee Student
\ /
\ /
\ /
+ +
WorkingStudent

class WorkingStudent : public Student, public Employee


{
// ...
}

• Mia klˆsh mporeÐ na parˆgetai apì parapˆnw apì mia


basikèc klˆseic ˆmesa.
• S’ aut n thn perÐptwsh, klhronomeÐ ta mèlh apì ìlec tic
klˆseic.
• Se perÐptwsh sÔgkroushc onomˆtwn, gÐnetai qr sh tou
telest  ::
167

PROTUPA (templates)
• Sunart sewn
• Klˆsewn
168

Prìtupa Sunart sewn
• Genik  morf :
template< class T >

• p.q. antÐ,
void printArray(const int* array, const int count);
void printArray(const double* array, const int count);
// ...
kˆnoume
template < class T >
void printArray(const T* array, const int count)
{
for (int i=0; i < count; i++)
cout << array[i] << " ";
cout << endl;
}

• tìte prèpei na kˆnoume:


main()
{
const int aCount=5, bCount=7, cCount=6;
int a[aCount];
double b[bCount];
char c[cCount];
// ...
printArray(a, aCount);
printArray(b, bCount);
printArray(c, cCount);
}
169

Parathr seic sta prìtupa sunart sewn


• Epitugqˆnoun polumorfismì.
• Ta prìtupa epitrèpoun na orÐsoume èna sÔnolo
sqetizìmenwn sunart sewn (  èna sÔnolo apì
sqetizìmenec klˆseic).
• Grˆfoume ènan orismì gia th sunˆrthsh, perilambˆnontac
paramètrouc tÔpwn.
• Katˆ th metagl¸ttish, anˆloga me touc tÔpouc pou
emfanÐzontai sthn kl sh miac tètoiac sunˆrthshc,
parˆgetai k¸dikac gia thn kˆje mia perÐptwsh
• Parˆmetroi tÔpwn mporoÔn na emfanÐzontai:
– sta tupikˆ orÐsmata thc sunˆrthshc
– ston tÔpo pou epistrèfei h sunˆrthsh
– mèsa sto s¸ma thc sunˆrthshc
• Oi parˆmetroi tÔpwn prèpei na eÐnai monadikoÐ sta prìtupa.
170

Prìtupa Klˆsewn
• ParametrikoÐ tÔpoi.
• GenikoÐ orismoÐ klˆsewn me sugkekrimenopoÐhsh (ìqi
exeidÐkeush) me bˆsh sugkekrimènouc tÔpouc.
• Sthn epikefalÐda miac klˆshc mporoÔn na qrhsimopoihjoÔn
kai parˆmetroi pou den eÐnai tÔpoi, p.q.
template<class T, int elements>
class Stack
{
// ...
}
tìte,
Stack<double,100>

• MporeÐ na oristeÐ mia klˆsh gia èna sugkekrimèno tÔpo.


• Z thma: klhronomikìthta kai prìtupa klˆsewn.
171

Parˆdeigma: orismìc enìc protÔpou klˆshc, twn sunart sewn


mel¸n thc kai qr sh thc
Orismìc tou protÔpou:
template < class T >
class Stack
{
public:
Stack(int=10);
~Stack() { delete [] stackPtr; }
bool push(const T&);
bool pop(T&);

private:
int size;
int top;
T* stackPtr;

bool isEmpty() const { return top == -1 }


bool isFull() const { return top == size - 1 }
};
Orismìc sunart sewn -mel¸n:
template < class T >
Stack<T>::Stack(int s)
{
size = s>0?s:10;
top = -1;
stackPtr = new T[size];
}

template < class T >


bool Stack<T>::push(const T& pushValue)
{
if (!isFull())
{
stackPtr[++top] = pushValue;
return true;
}
return false;
}
// ...
172

Qr sh tou protÔpou:


main()
{
Stack<double> dStack(5); \\instantiation
Stack<int> iStack(20); \\instantiation
}
173

ALLES GLWSSIKES DOMES THS C++ (krÐsimec


gia tic klˆseic)
Klˆseic (perÐlhyh prohgoumènwn)
• H dom  pou eisˆgetai me th desmeumènh lèxh class ( 
struct).
• Diaqwrismìc private/public epitugqˆnei apìkruyh
plhroforÐac.
• DhmiourgÐa stigmiotÔpwn (antikeimènwn) pou “ktÐzontai”
apì ta mèlh -dedomèna (data members) thc klˆshc sthn
opoÐa an koun.
• DhmiourgÐa stigmiotÔpwn mèsw sunart sewn kataskeu c.
• Katastrof  stigmiotÔpwn mèsw sunˆrthshc katastrof c.
• Qeirismìc antikeimènwn mèsw sunart sewn -mel¸n
(member functions).
• Prìsbash sto antikeÐmeno gia to opoÐo kaleÐtai h
sunˆrthsh -mèloc me qr sh tou deÐkth this.
• Kataskeu  dia antigraf c.
• Qr sh telest  anˆjeshc.
174

AntikeÐmena const kai Sunart seic -mèlh const


• Gia thn efarmog  thc arq c tou “elˆqistou aparaÐthtou
dikai¸matoc”.
• Kˆpoia antikeÐmena den jèloume na metablhjoÔn katˆ th
diˆrkeia thc “zw c” touc.
• H qr sh thc lèxhc -kleidioÔ const dhl¸nei ìti to
antikeÐmeno den ja metablhjeÐ (kai kˆje enèrgeia proc to
antÐjeto dhmiourgeÐ suntaktikì lˆjoc).
• Parˆdeigma:
class Time
{
public:
Time(int=0, int=0, int=0);
void settime(int, int, int);
// ...
private:
int hour;
int minute;
int second;
};

// ...

const Time noon(12,0,0);


S’ aut n thn perÐptwsh, oi mìnec sunart seic pou mporoÔn
na efarmostoÔn se autˆ ta antikeÐmena eÐnai ekeÐnec oi
sunart seic -mèlh pou èqei dhlwjeÐ ìti den metabˆloun ta
antikeÐmena sta opoÐa efarmìzontai.
• To parapˆnw epitugqˆnetai me th qr sh thc lèxhc
175

-kleidioÔ const tìso sth d lwsh ìso kai ston orismì thc
sunˆrthshc -mèlouc (jètontˆc to metˆ tic paramètrouc thc
sunˆrthshc).
class Time
{
public:
// ...
int getHour() const;
int getMinute() const;
int getSecond() const;
// ...
};

// ...

int Time::getHour() const


{ return hour; }

int Time::getMinute() const


{ return minute; }

int Time::getSecond() const


{ return second; }

• Mpor¸ na èqw uperfìrtwsh gia tic const sunart seic


-mèlh me non -const ekdoqèc touc.
• H epilog  gia th qr sh miac const   non -const ekdoq c
miac sunˆrthshc -mèlouc gÐnetai apì to metaglwttist  me
bˆsh to eˆn efarmìzetai se const antikeÐmeno   ìqi.
176

Filikèc Sunart seic kai Filikèc Klˆseic


• Mia klˆsh mporeÐ na dhl¸sei mia sunˆrthsh pou den eÐnai
sunˆrthsh -mèloc thc wc filik  (me th qr sh thc lèxhc
-kleidioÔ friend).
• H sunˆrthsh aut  parìlo pou den eÐnai sthn embèleia thc
klˆshc, èqei dikaÐwma na èqei prìsbash sto idiwtikì mèroc
thc klˆshc.
• Autì eÐnai idiaÐtera qr simo sthn perÐptwsh orismoÔ
telest¸n kai sunart sewn epanˆlhyhc (iterators).
• San filikèc mporoÔn na dhlwjoÔn kai olìklhrec klˆseic
(pˆli me th qr sh thc lèxhc -kleidioÔ friend). p.q.
class NewClass
{
// ...
friend class FriendClass;
// ...
};
177

Parˆdeigma qr shc filik¸n sunart sewn


class Count
{
friend void setX(Count&, int); // friend declaration

public:
Count() { x= 0}
void print() const { cout << x << endl; }

private:
int x;
};

void setX(Count& c, int val)


{
c.x = val; // Access to private part
}

int main()
{
Count counter;
counter.print();
setX(counter,8);
counter.print();
return 0;
}
178

Parathr seic sth “filÐa”


• Oi filikèc sunart seic den apoteloÔn sunart seic -mèlh
thc klˆshc (apl¸c tuqaÐnei na paÐrnoun èna antikeÐmeno
thc klˆshc stic paramètrouc touc).
• Dhl¸seic friend mporoÔn na emfanistoÔn opoud pote
mèsa ston orismì miac klˆshc (den ephreˆzei an eÐnai mèsa
sto private   sto public mèroc touc)
• H filÐa den eÐnai oÔte summetrik  oÔte metabatik  metaxÔ
twn klˆsewn, oÔte klhronomeÐtai.
179

Statikˆ Mèlh Klˆsewn


• Kˆje antikeÐmeno miac klˆshc èqei to dikì tou antÐgrafo
gia kˆje mèloc -dedomèno thc klˆshc (“qtÐzetai” apì
autˆ).
• Upˆrqoun peript¸seic pou jèloume ìla ta antikeÐmena na
moirˆzontai to Ðdio antÐgrafo gia mia metablht .
• Autì epitugqˆnetai me th qr sh thc lèxhc -kleidioÔ static
katˆ th d lwsh thc metablht c ston orismì thc klˆshc.
• H embèleia twn statik¸n mel¸n miac klˆshc eÐnai h klˆsh
kai mporoÔn na dhlwjoÔn wc private   public (  protected).
• Ta statikˆ mèlh klˆsewn prèpei na arqikopoioÔntai (kai
mìno mia forˆ) se epÐpedo embèleiac arqeÐou.
180

Parˆdeigma:
D lwsh statik¸n mel¸n:
// employee.h
class Employee
{
public:
Employee(const char*, const char*);

~Employee();

const char* getFirstName() const;


const char* getLastName() const;

static int getCount(); // <- static member function

private:
char* firstName;
char* lastName;

static int count; // <- static variable


};
Orismìc kai arqikopoÐhsh:
// employee.cc
# ...
#include employee.h

int Employee::count = 0; // <- Initialization

int Employee::getCount() { return count; }

Employee::Employee(const char* first, const char* last)


{
firstName = new char[strlen(first) + 1];
strcpy( firstName, first );

lastName = new char[strlen(last) + 1];


strcpy( lastName, last );

++count // <- Usage within class


}
181

Employee::~Employee()
{
delete [] firstName;
delete [] lastName;

--count; // <- Usage within class


}
// ...

Qr sh statik¸n mel¸n:


// test.cc
# ...
#include employee.h

int main()
{
// Access with class scope:
cout << Employee::getCount() << endl;

Employee* e1 = new Employee( "FN1", "LN1" );


Employee* e2 = new Employee( "FN2", "LN2" );

// Access via a class object:


cout << e1->getCount();

delete e1;
delete e2;

// No problem if no class object exits,


// access with class scope, again:
cout << Employee::getCount() << endl;

return = 0;
}
182

Parathr seic sta statikˆ mèlh klˆsewn


• MporoÔme na èqoume prìsbash sta public static mèlh miac
klˆshc
– eÐte mèsw enìc antikeimènou thc klˆshc
– eÐte me qr sh tou onìmatoc thc klˆshc kai tou telest 
::
• 'Exw apì thn klˆsh mporoÔme na èqoume prìsbash sta
static private (  protected) mèlh mèsw public sunart sewn
-mel¸n   filik¸n sunart sewn.
• Ta statikˆ mèlh twn klˆsewn èqoun upìstash anexˆrthta
apì th dhmiourgÐa   ìqi antikeimènwn thc klˆshc.
• Sthn parapˆnw perÐptwsh, mporoÔme na èqoume prìsbash,
èxw apì thn klˆsh sta public static mèlh thc,
qrhsimopoi¸ntac to ìnoma thc klˆshc kai ton telest  ::
• 'Otan den èqoun dhmiourghjeÐ antikeÐmena miac klˆshc, gia
na èqoume prìsbash se private (  protected) static mèlh
thc klˆshc, èxw apì thn klˆsh, prèpei na èqei oristeÐ mia
public static sunˆrthsh -mèloc thc klˆshc kai na klhjeÐ me
to ìnoma thc klˆshc kai qr sh tou telest  ::
• De mporoÔme na qrhsimopoi soume to deÐkth this se mia
static sunˆrthsh -mèloc miac klˆshc.
• De mporoÔme na dhl¸soume mia static sunˆrthsh -mèloc
san const.
• Ta statikˆ mèlh -dedomèna kai oi statikèc sunart seic
-mèlh miac klˆshc upˆrqoun kai mporoÔn na
qrhsimopoihjoÔn akìma ki an den èqoun dhmiourghjeÐ
antikeÐmena thc klˆshc.
183

METATROPES TUPWN
• MporeÐ na qreiasteÐ na metatrèyoume rhtˆ mia tim , pou
eÐnai kˆpoiou tÔpou, se kˆpoion ˆllo tÔpo. p.q.
float r = float(1);
metatrèpei ton akèraio 1 ston pragmatikì 1.0f gia na
dojeÐ san tim  ston pragmatikì r.
• Upˆrqoun dÔo trìpoi na to sumbolÐsoume:
1. (à la C): cast, me th qr sh parenjèsewn, p.q.
(double) a
2. “sunarthsiak ” graf :
double(a)
den mporeÐ ìmwc na qrhsimopoihjeÐ gia tÔpouc pou
èqoun sÔnjeto sumbolismì. p.q.
OQI char*(0777);
MONO (char*) 0777;
• Sth C++ den upˆrqei tìso èntonh anˆgkh gia rht 
metatrop  tÔpwn, antÐjeta me th C.
• Stouc deÐktec, anˆjesh apì/se void* den qreiˆzetai rht 
metatrop  tÔpou.
• Autìmath metatrop  tÔpwn, orismènh apì ton qr sth:
– mèsw orismoÔ sunart sewn kataskeu c (tou tÔpou
-proc me ìrisma tou tÔpou -apì)
– mèsw orismoÔ telest¸n (tou tÔpou -proc pou
efarmìzontai ston tÔpo -apì)
• Rht  metatrop  tÔpwn (gia na agno soume teleÐwc tic
metatropèc à la C):
184

static cast : gia “asfaleÐc” metatropèc pou ja èkane


oÔtwc   ˆllwc o metaglwttist c   ligìtero asfaleÐc
allˆ kalˆ orismènec
const cast : gia na parabiˆsoume d lwsh const ( 
volatile)
reinterprete cast : EPIKINDUNO: ermhneÔei to
antikeÐmeno san na  tan akoloujÐa apì bits. (Prèpei na
to “epanafèroume” prin to xanaqeiristoÔme omalˆ)
dynamic cast : “asfal c” metˆbash se qamhlìterh
klˆsh sthn ierarqÐa.
185

BibliografÐa
• Bjarne Stroustrup, “H Gl¸ssa ProgrammatismoÔ C++”
(TrÐth Amerikˆnikh 'Ekdosh), ekdìseic “Kleidˆrijmoc”,
1999
• Bruce Eckel, “Thinking In C++” (Second Edition),
Volume One: Introduction to Standard C++, Prentice
Hall, 2000
• ISO International Standard: Programming Languages —
C++, 1998
• Stanley B. Lippman, Josee Lajoie, “C++ Primer” (3rd
Edition), Addison-Wesley, 1998
• Stanley B. Lippman, “Inside the C++ Object Model”
Addison-Wesley, 1996
• Herbert Schildt, “C++: The Complete Reference” (2nd
Edition), McGraw-Hill, 1995
• Till Jeske, “C++ Nitty Gritty”, Addison-Wesley, 2000
(Pearson Education, 2002)
• The Standard Template Library:
http://www.sgi.com/tech/stl
• Bertrand Meyer, “Object -Oriented Software
Construction” (2nd Edition), Prentice Hall, 2000
• Russel Winder, Graham Roberts, “Developing Java
Software” (2nd Edition), John Wiley and Sons, 2000
186

Vous aimerez peut-être aussi