Introduction. Me Dr inż. Roman Starosolski Room nr 527 (timetable, consultations etc.)...
-
Upload
zoie-thomas -
Category
Documents
-
view
213 -
download
0
Transcript of Introduction. Me Dr inż. Roman Starosolski Room nr 527 (timetable, consultations etc.)...
MeMe
Dr inż. Roman StarosolskiDr inż. Roman Starosolski
Room nr 527 (timetable, consultations etc.)Room nr 527 (timetable, consultations etc.)
roman.starosolskiroman.starosolski@@polslpolsl.pl.pl
http://sun.http://sun.aeiaei.polsl.pl/~rstaros/.polsl.pl/~rstaros/S/S/CCp3p3// course regulationscourse regulations course materialscourse materials useful resourcesuseful resources
PlanPlan
1.1. IntroductionIntroduction
2.2. Not object orientedNot object oriented C++ extensionsC++ extensions
3.3. OOP, class, objectOOP, class, object
4.4. Constructor, destructorConstructor, destructor
5.5. OperatorOperatorss
6.6. static, const static, const andand volatile volatile
7.7. InheritanceInheritance, , derived classesderived classes
8.8. Virtual methodsVirtual methods
9.9. Multiple inheritanceMultiple inheritance
10.10. TemplatesTemplates
11.11. ExceptionsExceptions
12.12. LibrariesLibraries
C++ historyC++ history
C++ is, but some minor details, a superset of C++ is, but some minor details, a superset of the C language (both alive)the C language (both alive)
C is a successor of BCPL language (dead)C is a successor of BCPL language (dead) there was no A languagethere was no A language
C++ — a C with classesC++ — a C with classes
data abstraction tooldata abstraction tool object oriented programming languageobject oriented programming language better Cbetter C
Books on C++Books on C++
Bjarne Stroustrup „Język C++” WNT W-wa Bjarne Stroustrup „Język C++” WNT W-wa International Standard for Information
Systems—Programming Language C+ + (draft), ANSI
Books on C++Books on C++
Stroustrup B.: Projektowanie i rozwój języka Stroustrup B.: Projektowanie i rozwój języka C++. WNT, WarszawaC++. WNT, Warszawa
Plauger P.J., Biblioteka standardowa C ++. Plauger P.J., Biblioteka standardowa C ++. WNT, WarszawaWNT, Warszawa
Books on C++Books on C++
Lippman S.B., Lajoie J.: Podstawy języka C+Lippman S.B., Lajoie J.: Podstawy języka C++. WNT, Warszawa +. WNT, Warszawa
Tondo C. L., Leung B. P.: Podstawy języka Tondo C. L., Leung B. P.: Podstawy języka C++. Ćwiczenia i rozwiązania. WNT, C++. Ćwiczenia i rozwiązania. WNT, Warszawa Warszawa
Grębosz J.: Symfonia C++. RM, W-wa, Grębosz J.: Symfonia C++. RM, W-wa, wyd. 4.wyd. 4.
Grębosz J.: Pasja C++. RM, W-wa, wyd. 2.Grębosz J.: Pasja C++. RM, W-wa, wyd. 2.
CommentComment
/* /* C comment, valid also in C++,C comment, valid also in C++,may be several lines long */may be several lines long */
// C++ one line comment // C++ one line comment
// ends with End// ends with End OfOf LineLine
CommentComment
We may still use the preprocessor to comment We may still use the preprocessor to comment out large blocks of source codeout large blocks of source code
#if 0#if 0
/* /* C comment, valid also in C++,C comment, valid also in C++,may be several lines long */may be several lines long */
// C++ comment ends with End// C++ comment ends with End OfOf LineLine
#endif#endif
CommentComment
/* /* use C comment, or a C++ commentuse C comment, or a C++ commentfor several lines long comments */for several lines long comments */
// // however, do not mix them !!!however, do not mix them !!!
void foo()void foo() // here stick to C++ comments// here stick to C++ comments{{
return; return; // they are more convenient// they are more convenient}}
Standard input and outputStandard input and output We may still use C <stdio.h> functionsWe may still use C <stdio.h> functions We should use C++ <iostream.h> operatorsWe should use C++ <iostream.h> operators
#include <iostream.h>#include <iostream.h>int a,b,c,d;int a,b,c,d;cout << „input a and b \n” ;cout << „input a and b \n” ;cin >> a;cin >> a;cin >> b; cin >> b;
cout << „input c and d \n” cout << „input c and d \n” cin >> c >> d;cin >> c >> d;
Standard input and outputStandard input and output Streams are not so susceptible to errors as <stdio.h> (vide Streams are not so susceptible to errors as <stdio.h> (vide
scanfscanf() () ))
StreamsStreams cin cin - std. input- std. input coutcout - std- std.. output output cerrcerr - std- std.. error output error output
Manipulating strings, setting precision, checking stream status, Manipulating strings, setting precision, checking stream status, etc. – as functional as in <stdio.h> etc. – as functional as in <stdio.h>
We should not mix C++ <iostream.h> operators and <stdio.h> We should not mix C++ <iostream.h> operators and <stdio.h> functionsfunctions
Declarations are statementsDeclarations are statements declaration inside block is a statementdeclaration inside block is a statement it may be placed after other statementsit may be placed after other statements
{{int i=12;int i=12;cout << „statement”;cout << „statement”;
int j=i;int j=i;for (for (int int k=0; k<20; k++)k=0; k<20; k++)
j+=k;j+=k;}}
Declaration in „for”Declaration in „for”
int i = 42;int a[10];
for (int i = 0; i < 10; i++)a[i] = i;
int j = i; // j = 42
Declaration in „for”Declaration in „for”
for ( forinitstatement; condition; expression )
is equivalent to
{forinitstatementwhile ( condition ) {
statementexpression ;
}}
gotogoto
more restrictions than in C:more restrictions than in C: inside block onlyinside block only cannot jump over initializationcannot jump over initialization
gotogoto
a:a:
int foo()int foo()
{{
b:b:
goto b;goto b;
int i=7;int i=7;
c:c:
return i;return i;
}}
d:d:
void foofoo()void foofoo()
{{
e:e:
return;return;
}}
TypesTypes
strong type control (as compared to C) – to strong type control (as compared to C) – to permit error detection by compilerpermit error detection by compiler
automatic type conversions – when it does not automatic type conversions – when it does not lead to ambiguitylead to ambiguity
whenever it is possible no whenever it is possible no precision or precision or information is lost (not guaranteed for all information is lost (not guaranteed for all conversions: conversions: char/short/int/long/single/float/double/signed/uchar/short/int/long/single/float/double/signed/unsigned)nsigned)
TypesTypes
int type assumed when no type specifiedint type assumed when no type specified
unsigned u;unsigned u;
const a; const a;
static i; static i;
explicit specifying the int type is advicedexplicit specifying the int type is adviced
Type void *Type void *
no automatic conversion to other pointer typesno automatic conversion to other pointer types
void *malloc(size_t size);void *malloc(size_t size);
char *str;char *str;
int *pi;int *pi;
str = (char *) malloc(10)str = (char *) malloc(10);;
pi = (int *)malloc(100);pi = (int *)malloc(100);
Type void *Type void *
automatic conversion from any pointer typeautomatic conversion from any pointer type(but const * and volatile * types)(but const * and volatile * types)
void free(void *block);void free(void *block);
free(str);free(str);
free(pi)free(pi);;
constconst
named constants are to replace #defined C constantsnamed constants are to replace #defined C constants
const five = 5; const five = 5; void fooj(const int ci);void fooj(const int ci);
constconstss – regular variables, with address, size, – regular variables, with address, size, operators, but not to be modified operators, but not to be modified
const prevents programmer from mistakesconst prevents programmer from mistakes use of constuse of constss permits optimization by a compiler permits optimization by a compiler
const and pointersconst and pointers
pointer to const: const char *pc=”asdf”pointer to const: const char *pc=”asdf”(or char const *pc=”asdf”)(or char const *pc=”asdf”)
const pointer: char * const cp=”asdcf”;const pointer: char * const cp=”asdcf”; const pointer to const:const pointer to const:
const char * const cpc=”asdcf”; const char * const cpc=”asdcf”;
mistakes: pc[1]=‘2’; cp++; cpc[1]=‘b’; cpc--;mistakes: pc[1]=‘2’; cp++; cpc[1]=‘b’; cpc--;
it is ok. to assign address of non-const to pointer to it is ok. to assign address of non-const to pointer to constconst
enumenum
enum numbers {ZERO, ONE, FIVE=5, SIX}; enum numbers {ZERO, ONE, FIVE=5, SIX};
„„numbers” is optional name of a new typenumbers” is optional name of a new type conversion from enum to int is automaticconversion from enum to int is automatic
why enum is not so popular?why enum is not so popular?
ReferencesReferences
reference to type T: T& reference to type T: T&
it is a pointer that looks like a variableit is a pointer that looks like a variable
int i=7, int i=7, // variable// variableint & iref=i;int & iref=i; // reference must be initialized// reference must be initialized
// i.e. associated with something (i)// i.e. associated with something (i)iref++;iref++; // now i==8 // now i==8
ReferencesReferences
void swap(int &i1, int &i2); void swap(int &i1, int &i2); int a=2, b=3;int a=2, b=3;
swap(a,b);swap(a,b);
void swap(int &i1, int &i2) void swap(int &i1, int &i2) {{
int i3;int i3;i3=i1;i3=i1;i1=i2;i1=i2;i2=i3;i2=i3;
}}
i1i1 i2i2 i3i3 aa bb
-- -- -- 22 33-- -- -- 33 22
22 33 -- 22 33
22 33 ?? 22 3322 33 22 22 3333 33 22 33 3333 22 22 33 22
References – problemsReferences – problems problem: actual parameter type is not the same as problem: actual parameter type is not the same as
formal, or is an expressionformal, or is an expression
char c;char c;swap(a+20, c);swap(a+20, c);
arguments are converted to const (const int), compiler arguments are converted to const (const int), compiler expects int (not const), it should exit with error, expects int (not const), it should exit with error, usually issues only a warning.usually issues only a warning.
obviously nothing gets swappedobviously nothing gets swapped
References – problemsReferences – problems
// int &ir=7; ERROR! 7 is constant// int &ir=7; ERROR! 7 is constant
const int &ir1=7, const int &ir1=7, // OK// OK
&ir2=i+f; &ir2=i+f; // OK// OK
/* ir1 and ir2 – references to constant temporary /* ir1 and ir2 – references to constant temporary objects living as long as ir1 and ir2 */objects living as long as ir1 and ir2 */
References – an useful exampleReferences – an useful example
int & min(int &i1, int&i2)int & min(int &i1, int&i2){{
return i1return i1<<i2 ? i1 : i2;i2 ? i1 : i2;}}
int a=10, b=20, c;int a=10, b=20, c;c=min(a,b);c=min(a,b);
min(a,b)++; //now a==11 !min(a,b)++; //now a==11 !
ReferencesReferences
may be misleading may be misleading avoid functions that alter its argumentsavoid functions that alter its arguments
use it when You actually need ituse it when You actually need it for saving memoryfor saving memory for saving timefor saving time for returning objects to be further processedfor returning objects to be further processed
use const referencesuse const references
Functions – PrototypesFunctions – Prototypes
Function prototypes are required!!!Function prototypes are required!!!(return value, name, arguments)(return value, name, arguments)
#include „foo_prototypes.h”#include „foo_prototypes.h”
void foo();void foo();
void foo() {};void foo() {};
Functions – inlineFunctions – inline
inline int sum(int a, int b)inline int sum(int a, int b){{
return a+b;return a+b;}}
destined to replace macro definitionsdestined to replace macro definitions inline keyword is only a recommendation for inline keyword is only a recommendation for
compilercompiler automatic inline function expansionautomatic inline function expansion function expanded inline has no addressfunction expanded inline has no address
Overloaded functionsOverloaded functions
many functions, the same name, OK. in C++many functions, the same name, OK. in C++
int f(int, int); int f(int, int);
int f(int); int f(int);
int f(long); int f(long);
Overloaded functionsOverloaded functions
Address of the overloaded function – compiler Address of the overloaded function – compiler has to know which one to pickhas to know which one to pick
int (*pd)(long);int (*pd)(long); //OK//OKpd=f;pd=f;
void *pf;void *pf; // pf=f;// pf=f; // ERROR!// ERROR!
Overloaded functionsOverloaded functions Parameters of overloaded function must differ,Parameters of overloaded function must differ, Type returned is not considered during compilation, it Type returned is not considered during compilation, it
is examined when function is calledis examined when function is called
int f(int, int); int f(int); int f(long); // OKint f(int, int); int f(int); int f(long); // OK// int f(int); double f(int); ERROR// int f(int); double f(int); ERROR
int fint fff(int); int f(int); int fff(double); // OK.(double); // OK.// f// fff(1L) ERROR! ambiguous(1L) ERROR! ambiguous// void *p=f// void *p=fff(1) ERROR! type (1) ERROR! type
Matching overloaded functionsMatching overloaded functions no more then one conversion per argument pick lowest match level, ambiguity is an error
1. exact match (no conversion, but table to pointer, function to pointer, T to const T)
2. promotions (int to long, char to int, unsigned to long unsigned, float to double, etc.)
3. standard conversions (unsigned int ↔ int, int ↔ double, derived * to base *)
4. user defined conversions5. variable argument list (…)
Matching overloaded functionsMatching overloaded functions
int f(int);double f(double)void f();
int i1=f(1); // OKint i2=f(1.0); // OK, call double f(double),
// then convert result to int//int i3=f(„Hi”); ERROR! no standard conversion// char * to int or double
Overloaded functionsOverloaded functions convenient extension of manual and automatic conversionsconvenient extension of manual and automatic conversions
int cmp (double a, double b)int cmp (double a, double b) {{
return areturn a – – b;b;}}
int cmp (char *a, char *b)int cmp (char *a, char *b) {{
return strcmp(a,b);return strcmp(a,b);}}
Overloaded functionsOverloaded functions we still benefit from automatic conversionswe still benefit from automatic conversions
cmp (1, 2);cmp (1, 2); //OK., conversion to double prior //OK., conversion to double prior //to call cmp (double a, double b)//to call cmp (double a, double b)
we may improve code performancewe may improve code performance
int cmp (int a, int b)int cmp (int a, int b) // now cmp(1, 2) without conversion// now cmp(1, 2) without conversion{{
return areturn a – – b;b;}}
Default function argumentsDefault function arguments
void line(int len, char c=‘*’)void line(int len, char c=‘*’){{
for (int i=0; i<len; i++)for (int i=0; i<len; i++)cout << c;cout << c;
}}
now this: now this: line(x);line(x);means:means: line(x, ‘*’);line(x, ‘*’);
and this: and this: line(x, ‘o’);line(x, ‘o’);means:means: line(x, ‘o’);line(x, ‘o’);
Default function argumentsDefault function arguments
int fun(int i1, int i2=20, int i3=30);int fun(int i1, int i2=20, int i3=30);
starting from first default argument, all remaining starting from first default argument, all remaining also have to be defaultalso have to be default
function with default arguments is not overloaded, function with default arguments is not overloaded,
&fun(int) == &fun(int, int)&fun(int) == &fun(int, int) we may overload: we may overload:
int fun(int i1, int i2); //declaration is not int fun(int i1, int i2); //declaration is not ambiguous, //but the call fun (int, int) is! ambiguous, //but the call fun (int, int) is!
Default function argumentsDefault function arguments
mind the „type * =” mind the „type * =” — — „„==” must be ” must be preceded by spacepreceded by space
defaults may be defined only once (formally defaults may be defined only once (formally either in prototype or in definition).either in prototype or in definition).
Advice: define overloads in a header file!Advice: define overloads in a header file!
Variable function argument listVariable function argument list in C we wrote:in C we wrote:
int printf(char *, …);int printf(char *, …);
in C++ it is so much simpler:in C++ it is so much simpler:int printf(char * …); int printf(char * …); // comma not required, but only if // comma not required, but only if // variable preceding „…” has no default value.// variable preceding „…” has no default value.// Macros for accessing args still in <stdarg.h >// Macros for accessing args still in <stdarg.h >
in C++ it is so much simpler:in C++ it is so much simpler:use overloading instead variable argument listuse overloading instead variable argument list
Memory managementMemory management allocating memory: operator newallocating memory: operator new
syntax: new Typesyntax: new Type
int * pi = new int; int * pi = new int; // pi = (int*)malloc(sizeof(int))// pi = (int*)malloc(sizeof(int))
deallocating: operator deletedeallocating: operator deletesyntax: delete pointersyntax: delete pointer
delete pi; // pi value not altered by delete operatordelete pi; // pi value not altered by delete operator
Memory managementMemory management dealing with vectors (arrays)dealing with vectors (arrays)
int * pai = new int [x]; int * pai = new int [x]; delete [] pai; delete [] pai;
programmer must remember whether pointer points to scalar programmer must remember whether pointer points to scalar or vector (compiler does not check)or vector (compiler does not check)
multidimensional arraysmultidimensional arraysint *pmai = new int[x][20][30] int *pmai = new int[x][20][30]
// all dimensions, but the first one have to// all dimensions, but the first one have to// be known at the compilation time// be known at the compilation time
delete [] pmai;delete [] pmai;
Memory managementMemory management
we may define function (new_handler) to call when we may define function (new_handler) to call when there is not enough memory there is not enough memory
set_new_handler(); //<new.h>set_new_handler(); //<new.h>
if new_handler is not defined new returns 0 (NULL) if new_handler is not defined new returns 0 (NULL)
delete NULL; does nothing delete NULL; does nothing
do not mix new/delete and malloc/freedo not mix new/delete and malloc/free