c++ presentation 12112007
TRANSCRIPT
-
8/7/2019 C++ Presentation 12112007
1/226
-
8/7/2019 C++ Presentation 12112007
2/226
-
8/7/2019 C++ Presentation 12112007
3/226
-
8/7/2019 C++ Presentation 12112007
4/226
-
8/7/2019 C++ Presentation 12112007
5/226
-
8/7/2019 C++ Presentation 12112007
6/226
-
8/7/2019 C++ Presentation 12112007
7/226
-
8/7/2019 C++ Presentation 12112007
8/226
-
8/7/2019 C++ Presentation 12112007
9/226
-
8/7/2019 C++ Presentation 12112007
10/226
-
8/7/2019 C++ Presentation 12112007
11/226
-
8/7/2019 C++ Presentation 12112007
12/226
-
8/7/2019 C++ Presentation 12112007
13/226
-
8/7/2019 C++ Presentation 12112007
14/226
-
8/7/2019 C++ Presentation 12112007
15/226
-
8/7/2019 C++ Presentation 12112007
16/226
-
8/7/2019 C++ Presentation 12112007
17/226
-
8/7/2019 C++ Presentation 12112007
18/226
-
8/7/2019 C++ Presentation 12112007
19/226
-
8/7/2019 C++ Presentation 12112007
20/226
-
8/7/2019 C++ Presentation 12112007
21/226
-
8/7/2019 C++ Presentation 12112007
22/226
-
8/7/2019 C++ Presentation 12112007
23/226
-
8/7/2019 C++ Presentation 12112007
24/226
-
8/7/2019 C++ Presentation 12112007
25/226
-
8/7/2019 C++ Presentation 12112007
26/226
-
8/7/2019 C++ Presentation 12112007
27/226
-
8/7/2019 C++ Presentation 12112007
28/226
-
8/7/2019 C++ Presentation 12112007
29/226
-
8/7/2019 C++ Presentation 12112007
30/226
-
8/7/2019 C++ Presentation 12112007
31/226
-
8/7/2019 C++ Presentation 12112007
32/226
-
8/7/2019 C++ Presentation 12112007
33/226
-
8/7/2019 C++ Presentation 12112007
34/226
-
8/7/2019 C++ Presentation 12112007
35/226
-
8/7/2019 C++ Presentation 12112007
36/226
-
8/7/2019 C++ Presentation 12112007
37/226
-
8/7/2019 C++ Presentation 12112007
38/226
-
8/7/2019 C++ Presentation 12112007
39/226
-
8/7/2019 C++ Presentation 12112007
40/226
-
8/7/2019 C++ Presentation 12112007
41/226
-
8/7/2019 C++ Presentation 12112007
42/226
-
8/7/2019 C++ Presentation 12112007
43/226
-
8/7/2019 C++ Presentation 12112007
44/226
-
8/7/2019 C++ Presentation 12112007
45/226
-
8/7/2019 C++ Presentation 12112007
46/226
-
8/7/2019 C++ Presentation 12112007
47/226
-
8/7/2019 C++ Presentation 12112007
48/226
-
8/7/2019 C++ Presentation 12112007
49/226
-
8/7/2019 C++ Presentation 12112007
50/226
-
8/7/2019 C++ Presentation 12112007
51/226
-
8/7/2019 C++ Presentation 12112007
52/226
-
8/7/2019 C++ Presentation 12112007
53/226
-
8/7/2019 C++ Presentation 12112007
54/226
-
8/7/2019 C++ Presentation 12112007
55/226
-
8/7/2019 C++ Presentation 12112007
56/226
-
8/7/2019 C++ Presentation 12112007
57/226
-
8/7/2019 C++ Presentation 12112007
58/226
-
8/7/2019 C++ Presentation 12112007
59/226
-
8/7/2019 C++ Presentation 12112007
60/226
-
8/7/2019 C++ Presentation 12112007
61/226
-
8/7/2019 C++ Presentation 12112007
62/226
-
8/7/2019 C++ Presentation 12112007
63/226
-
8/7/2019 C++ Presentation 12112007
64/226
-
8/7/2019 C++ Presentation 12112007
65/226
-
8/7/2019 C++ Presentation 12112007
66/226
-
8/7/2019 C++ Presentation 12112007
67/226
-
8/7/2019 C++ Presentation 12112007
68/226
-
8/7/2019 C++ Presentation 12112007
69/226
-
8/7/2019 C++ Presentation 12112007
70/226
-
8/7/2019 C++ Presentation 12112007
71/226
-
8/7/2019 C++ Presentation 12112007
72/226
-
8/7/2019 C++ Presentation 12112007
73/226
-
8/7/2019 C++ Presentation 12112007
74/226
-
8/7/2019 C++ Presentation 12112007
75/226
-
8/7/2019 C++ Presentation 12112007
76/226
-
8/7/2019 C++ Presentation 12112007
77/226
-
8/7/2019 C++ Presentation 12112007
78/226
-
8/7/2019 C++ Presentation 12112007
79/226
-
8/7/2019 C++ Presentation 12112007
80/226
-
8/7/2019 C++ Presentation 12112007
81/226
-
8/7/2019 C++ Presentation 12112007
82/226
-
8/7/2019 C++ Presentation 12112007
83/226
-
8/7/2019 C++ Presentation 12112007
84/226
-
8/7/2019 C++ Presentation 12112007
85/226
-
8/7/2019 C++ Presentation 12112007
86/226
-
8/7/2019 C++ Presentation 12112007
87/226
-
8/7/2019 C++ Presentation 12112007
88/226
-
8/7/2019 C++ Presentation 12112007
89/226
-
8/7/2019 C++ Presentation 12112007
90/226
-
8/7/2019 C++ Presentation 12112007
91/226
-
8/7/2019 C++ Presentation 12112007
92/226
-
8/7/2019 C++ Presentation 12112007
93/226
-
8/7/2019 C++ Presentation 12112007
94/226
-
8/7/2019 C++ Presentation 12112007
95/226
-
8/7/2019 C++ Presentation 12112007
96/226
-
8/7/2019 C++ Presentation 12112007
97/226
-
8/7/2019 C++ Presentation 12112007
98/226
-
8/7/2019 C++ Presentation 12112007
99/226
-
8/7/2019 C++ Presentation 12112007
100/226
-
8/7/2019 C++ Presentation 12112007
101/226
-
8/7/2019 C++ Presentation 12112007
102/226
-
8/7/2019 C++ Presentation 12112007
103/226
-
8/7/2019 C++ Presentation 12112007
104/226
-
8/7/2019 C++ Presentation 12112007
105/226
-
8/7/2019 C++ Presentation 12112007
106/226
-
8/7/2019 C++ Presentation 12112007
107/226
-
8/7/2019 C++ Presentation 12112007
108/226
-
8/7/2019 C++ Presentation 12112007
109/226
-
8/7/2019 C++ Presentation 12112007
110/226
-
8/7/2019 C++ Presentation 12112007
111/226
-
8/7/2019 C++ Presentation 12112007
112/226
-
8/7/2019 C++ Presentation 12112007
113/226
-
8/7/2019 C++ Presentation 12112007
114/226
-
8/7/2019 C++ Presentation 12112007
115/226
-
8/7/2019 C++ Presentation 12112007
116/226
-
8/7/2019 C++ Presentation 12112007
117/226
-
8/7/2019 C++ Presentation 12112007
118/226
-
8/7/2019 C++ Presentation 12112007
119/226
-
8/7/2019 C++ Presentation 12112007
120/226
-
8/7/2019 C++ Presentation 12112007
121/226
-
8/7/2019 C++ Presentation 12112007
122/226
-
8/7/2019 C++ Presentation 12112007
123/226
-
8/7/2019 C++ Presentation 12112007
124/226
-
8/7/2019 C++ Presentation 12112007
125/226
-
8/7/2019 C++ Presentation 12112007
126/226
-
8/7/2019 C++ Presentation 12112007
127/226
-
8/7/2019 C++ Presentation 12112007
128/226
-
8/7/2019 C++ Presentation 12112007
129/226
-
8/7/2019 C++ Presentation 12112007
130/226
-
8/7/2019 C++ Presentation 12112007
131/226
-
8/7/2019 C++ Presentation 12112007
132/226
Functions Returning Reference
F unctions returning referencesF unctions returning references
-
8/7/2019 C++ Presentation 12112007
133/226
g
C++ allows us to return values by reference.Listing: A C++ program returning a reference.
# include
int & func_name(int &);
void main(void){int x=10;int y=func_name(x);
contd on t h e next slide...
l f
-
8/7/2019 C++ Presentation 12112007
134/226
cout
-
8/7/2019 C++ Presentation 12112007
135/226
Pointers to Functions *y
A function pointer is a variable that can hold the addressof a function.
y When the operating system loads the .exe file of aprogram in the memory, each function of the programsegment gets loaded at a certain memory location whichis the address of that function.
y The name of the function gives the address of the function.
-
8/7/2019 C++ Presentation 12112007
136/226
Figure: Conceptual picture of an executable module loaded intothe memory
Listing: A C++ program to illustrate that the name of the
-
8/7/2019 C++ Presentation 12112007
137/226
g p gfunction gives the address of the function.
# include int func_name(int);void main(void){
cout
-
8/7/2019 C++ Presentation 12112007
138/226
The last program printed the following output in one run.
Address of the function func_name() is : 0x1b9002ad
Declaring t h e Function Pointer
-
8/7/2019 C++ Presentation 12112007
139/226
Declaring t h e Function Pointer
Consider the function with prototype declaration,
int func_name(char, int);
A pointer to this function is declared as follows:
int (* func_name_ptr)(char, int);
You can assign to the pointer the address of the function as:
func_name_ptr = func_name;
Listing: O verloaded functions and function pointers.
-
8/7/2019 C++ Presentation 12112007
140/226
# include
int func_name(char,int);int (*func_name_ptr1)(char,int);
void main(void){func_name_ptr1=func_name;cout
-
8/7/2019 C++ Presentation 12112007
141/226
The last program generated the following output in one run.
Value of func_name_ptr1 = 0x1b980310
The pointer variable func_name_ptr1 is assigned theaddress of the function whose return type and signature (i.e.argument list) matches with the return type and signature of the variable func_name_ptr1.
Invoking t h e Function Using t h e
-
8/7/2019 C++ Presentation 12112007
142/226
Invoking t h e Function Using t h e
Function Pointer Consider the following declarations:
int fun_name (char, int, double) - function prototypeint (* func_name_ptr) (char, int, double) - function pointer
The function can be invoked through the pointer like-
int x = (* func_num_ptr) (a, 10, 15.6) - invoking the function
Listing: A C++ program in which a function is invokedusing pointer.
-
8/7/2019 C++ Presentation 12112007
143/226
using pointer.
# include void hello_func(int);void(*hello_func_ptr)(int);
void main(void)
{hello_func_ptr=hello_func;(*hello_func_ptr)(4);}
output of t h is program is on t h e next slide...
void hello_func(int n){for(int i=0;i
-
8/7/2019 C++ Presentation 12112007
144/226
The last program prints the following output:
Hello WorldHello WorldHello WorldHello World
Pointer to A Function as Parameter
Pointers to a functionPointers to a function
-
8/7/2019 C++ Presentation 12112007
145/226
To A FunctionListing: A C++ program in which pointer to functions arepassed as parameters to functions.
# include void hello_world(int);void hello_Polaris(int);void (*hello_world_ptr)(int);void (*hello_Polaris_ptr)(int);
void func_name(int,void (*)(int));contd on t h e next slide...
void main(void)
-
8/7/2019 C++ Presentation 12112007
146/226
vo d a (vo d){
hello_world_ptr=hello_world;hello_Polaris_ptr=hello_Polaris;func_name(4,hello_world_ptr);cout
-
8/7/2019 C++ Presentation 12112007
147/226
{for(int i=0;i
-
8/7/2019 C++ Presentation 12112007
148/226
_________________________________________________________________________
The last program prints the following output:
Hello WorldHello WorldHello WorldHello WorldHello PolarisHello Polaris
When this program is compiled and the executable (lets
Exa m pl e contd..
-
8/7/2019 C++ Presentation 12112007
149/226
When this program is compiled and the executable (letssay) is called printstr, then typing the following commandfrom the U nix $ prompt:
$printstr string1 string2
will give the output:Th e two strings are not equal
CastingCasting
-
8/7/2019 C++ Presentation 12112007
150/226
gg
StaticStaticDynamicDynamicConstantConstantReinterpretReinterpret
ConstructorsConstructors
-
8/7/2019 C++ Presentation 12112007
151/226
C++ provides a special memberC++ provides a special memberfunction called constructor whichfunction called constructor whichenables an object to initialize itself enables an object to initialize itself when it is created. This is known aswhen it is created. This is known asautomatic initialization of objects.automatic initialization of objects.Constructors have the same nameConstructors have the same name
as the class name.as the class name.I t is invoked whenever an object of I t is invoked whenever an object of its associated class is createdits associated class is created
class integerclass integer
-
8/7/2019 C++ Presentation 12112007
152/226
{{
int m,n;int m,n;public: integer(void);//constructorpublic: integer(void);//constructor
declareddeclared....
}}integer:: integer(void) //constructorinteger:: integer(void) //constructordefineddefined
{{
m=0;n=0;m=0;n=0;}}
Parameterized ConstructorsParameterized Constructors
-
8/7/2019 C++ Presentation 12112007
153/226
Constructors that can takeConstructors that can takearguments are called parameterizedarguments are called parameterizedconstructorsconstructors
A constructor that accepts noA constructor that accepts noarguments is called the defaultarguments is called the defaultconstructor.constructor.
class integerclass integer{{
-
8/7/2019 C++ Presentation 12112007
154/226
{{int m,n;int m,n;public: integer(int x, int y);//parameterizedpublic: integer(int x, int y);//parameterized
constructorconstructor........
}}integer:: integer(int x, int y) //constructorinteger:: integer(int x, int y) //constructordefineddefined
{{m=x;m=x;n=y;n=y;
}}
D estructor D estructor
-
8/7/2019 C++ Presentation 12112007
155/226
A destructor is used to destroy theA destructor is used to destroy theobjects created by a constructor.objects created by a constructor.Like a constructor, the destructor is aLike a constructor, the destructor is amember function whose name is the samemember function whose name is the sameas the class but is preceded by a tilde.as the class but is preceded by a tilde.A destructor never takes any argumentA destructor never takes any argumentnor does it return any valuenor does it return any valueI t is invoked implicitly by the compilerI t is invoked implicitly by the compilerupon exit from the program to clean upupon exit from the program to clean upstorage that is no longer accessiblestorage that is no longer accessible
Inline functionsInline functions
-
8/7/2019 C++ Presentation 12112007
156/226
I nline function is a true function inI nline function is a true function inevery sense , the only difference isevery sense , the only difference isthat an inline function is expanded inthat an inline function is expanded in
place, like a preprocessor macro, soplace, like a preprocessor macro, sothe overhead of a function call isthe overhead of a function call iseliminated.eliminated.
Ex:Ex:inline int plusOne(int x) { return ++x; }inline int plusOne(int x) { return ++x; }
Inline functionsInline functions
-
8/7/2019 C++ Presentation 12112007
157/226
The inline code does occupy space,The inline code does occupy space,but if the function is small, this canbut if the function is small, this canactually take less space than the codeactually take less space than the code
generated to do ordinary functiongenerated to do ordinary functioncall.call.I t eliminates the overhead associatedI t eliminates the overhead associated
with pushing and popping parameterswith pushing and popping parameters
NamespacesNamespaces
-
8/7/2019 C++ Presentation 12112007
158/226
W hat is a Namespace?W hat is a Namespace?-- A namespace is a declarative region that can be usedA namespace is a declarative region that can be usedto package names, improve program readability andto package names, improve program readability andreduce name clashes in the global namespace.reduce name clashes in the global namespace.
Ex: namespace MySubsystem {Ex: namespace MySubsystem {class Fred{class Fred{ ------------ classclass MySubsystem::FredMySubsystem::Fred
// // };};
class W ilma{class W ilma{// // };};
void funct() {};void funct() {};}}
H ow to use namespaces:H ow to use namespaces:
Namespace People {Namespace People {
-
8/7/2019 C++ Presentation 12112007
159/226
int fred = 2; int wilma = 3; }int fred = 2; int wilma = 3; }void f() throw() {void f() throw() {int i = People::fred + People::wilma;int i = People::fred + People::wilma;
}}
Another approach:Another approach:void f2() throw() {void f2() throw() {
using People::fred;using People::fred;int i = fred + People::wilma;int i = fred + People::wilma;
}}
Another approach:Another approach:void f3() throw() {void f3() throw() {
using namespace People;using namespace People;int i = fred + wilma;int i = fred + wilma;
}}
S tatic class membersS tatic class members
-
8/7/2019 C++ Presentation 12112007
160/226
W hat are static class members?W hat are static class members?-- Static class members are data andStatic class members are data and
functions associated with the class itself functions associated with the class itself rather than the objects of the class.rather than the objects of the class.
-- Static data members are like dataStatic data members are like datalocated in the factory rather than in thelocated in the factory rather than in theobjects produced by the factory.objects produced by the factory.
-- Static member functions are likeStatic member functions are likeservices attached to the factory ratherservices attached to the factory ratherthan to the objects produced by thethan to the objects produced by thefactory.factory.
class car {class car {public:public:
-
8/7/2019 C++ Presentation 12112007
161/226
public:public:
static int num() throw(); //class servicestatic int num() throw(); //class servicevoid drive() throw(); //Object servicevoid drive() throw(); //Object service// You drive a car not a facory// You drive a car not a facoryprivate:private:static int num; //Class datastatic int num; //Class dataint miles_;//Object dataint miles_;//Object data
}}
int car::num()throw() //int car::num()throw() //{return num_;}{return num_;}
R eferencesR eferences
-
8/7/2019 C++ Presentation 12112007
162/226
A reference is an alias, an alternate nameA reference is an alias, an alternate namefor an object. References are frequentlyfor an object. References are frequentlypassing parameters by reference.passing parameters by reference.References cannot be made to reder to aReferences cannot be made to reder to adifferent referent.different referent.Ex:Ex:int main() {int main() {
int i=5;int i=5;
int j=6;int j=6;int& k =i; //k is an alias/reference to iint& k =i; //k is an alias/reference to ik = j; //does not bind k to jk = j; //does not bind k to j
Copy ConstructorsCopy Constructors
-
8/7/2019 C++ Presentation 12112007
163/226
Object pass by ref (X of X ref)Copy-construction
PolymorphismPolymorphism
-
8/7/2019 C++ Presentation 12112007
164/226
CompileCompile- -time Polymorphismtime Polymorphism-- Operator overloadingOperator overloading-- Function overloadingFunction overloading
RunRun--time Polymorphismtime Polymorphism-- Dynamic binding with VirtualDynamic binding with Virtual
functionsfunctions
Operator overloading is a special case of functionOperator overloading is a special case of functionl di hi h ll t i dditi ll di hi h ll t i dditi l
-
8/7/2019 C++ Presentation 12112007
165/226
overloading, which allows us to assign additionaloverloading, which allows us to assign additional
meanings to most of the standard C++meanings to most of the standard C++operators.operators.W hen overloading operators, it's good practice toW hen overloading operators, it's good practice to
ensure that the overloaded operator has a similarensure that the overloaded operator has a similarbehavior to the original operator.behavior to the original operator.For example, it would make more sense to useFor example, it would make more sense to usethe + operator for concatenation of strings thanthe + operator for concatenation of strings thanthe = operator.the = operator.Overloading operators does not change theOverloading operators does not change theprecedence and associativity of the operator.precedence and associativity of the operator.New operators cannot be introduced usingNew operators cannot be introduced usingoperator overloading.operator overloading.
I f we recall the abstract data type forI f we recall the abstract data type forcomplex numbers,complex numbers, Complex Complex , we could, we could
t C++ l f llt C++ l f ll
-
8/7/2019 C++ Presentation 12112007
166/226
create a C++ class as follows:create a C++ class as follows:
class Complex {class Complex {double _real, _imag;double _real, _imag;public: Complex() : _real(0.0),public: Complex() : _real(0.0),
_imag(0.0) {}_imag(0.0) {}Complex(const double real, constComplex(const double real, const
double imag) : _real(real),double imag) : _real(real),imag(imag) {}imag(imag) {}Complex add(const Complex op);Complex add(const Complex op);Complex mul(const Complex op); ... };Complex mul(const Complex op); ... };
W e would then be able to use complexW e would then be able to use complexnumbers and to ``calculate'' with them:numbers and to ``calculate'' with them:
-
8/7/2019 C++ Presentation 12112007
167/226
Complex a(1.0, 2.0), b(3.5, 1.2), c; c =Complex a(1.0, 2.0), b(3.5, 1.2), c; c =a.add(b);a.add(b);H ere we assignH ere we assign c c the sum of the sum of aa andand bb ..Although absolutely correct, it does notAlthough absolutely correct, it does notprovide a convenient way of expression.provide a convenient way of expression.W hat we would rather like to use is theW hat we would rather like to use is thewellwell--known ``+'' to express addition of known ``+'' to express addition of
two complex numbers. Fortunately, C++two complex numbers. Fortunately, C++allows us toallows us to overlo ad overlo ad almost all of itsalmost all of itsoperators for newly created types.operators for newly created types.
For example, we could define a ``+'' operator forFor example, we could define a ``+'' operator forour classour class Complex Complex ::
-
8/7/2019 C++ Presentation 12112007
168/226
class Complexclass Complex{ ... public: ... Complex operator +(const{ ... public: ... Complex operator +(constComplex &op)Complex &op){ double real = _real + op.real, imag = _imag +{ double real = _real + op.real, imag = _imag +op._imag; return(Complex(real, imag)); } ... };op._imag; return(Complex(real, imag)); } ... };I n this case, we have made operator + aI n this case, we have made operator + a
member of classmember of class Complex Complex . An expression of the. An expression of theformformc = a + b; is translated into a method call c =c = a + b; is translated into a method call c =a.operator +(b);a.operator +(b);Thus, the binary operator + only needs oneThus, the binary operator + only needs oneargument. The firstargument. The firstargument is implicitly provided by the invokingargument is implicitly provided by the invokingobject (in this caseobject (in this case aa ).).
H owever, an operator call can also be interpreted as aH owever, an operator call can also be interpreted as ausual function call, as in c = operator +(a, b); I n thisusual function call, as in c = operator +(a, b); I n thiscase the overloaded operator iscase the overloaded operator is notnot a member of aa member of a
-
8/7/2019 C++ Presentation 12112007
169/226
case, the overloaded operator iscase, the overloaded operator is notnot a member of aa member of aclass. I t is rather defined outside as aclass. I t is rather defined outside as a normal overloadednormal overloadedfunction. For example, we could define operator + in thisfunction. For example, we could define operator + in thisway:way:
class Complexclass Complex{ ... public: ... double real() { return _real; }{ ... public: ... double real() { return _real; }
double imag() { return _imag; }double imag() { return _imag; }// No need to define operator here! };// No need to define operator here! };Complex operator +(Complex &op1, Complex &op2)Complex operator +(Complex &op1, Complex &op2){ double real = op1.real() + op2.real(),{ double real = op1.real() + op2.real(),
imag = op1.imag() + op2.imag();imag = op1.imag() + op2.imag();return(Complex(real, imag)); }return(Complex(real, imag)); }
List of operators that can be overloadedList of operators that can be overloaded-- ! ~ +! ~ + - - * & / % >* & / % >
-
8/7/2019 C++ Presentation 12112007
170/226
-- < >= == != ^ | && ||< >= == != ^ | && ||-- +=+= - -= *= /= %= &= ^= |= == *= /= %= &= ^= |= =-- -->*>* --> () [] = ++> () [] = ++ -- -- new deletenew delete
List of operators that cannot be overloadedList of operators that cannot be overloaded-- . .* :: ?:. .* :: ?:
Wha t are t he b e n efi ts o f op era to r Wha t are t he b e n efi ts o f op era to r ov erl o adi ng?ov erl o adi ng?-- By overloading standard operators on a class,By overloading standard operators on a class,you canyou can
exploit the intuition of the users of that class.exploit the intuition of the users of that class.This letsThis lets
users program in the language of the problemusers program in the language of the problemdomaindomain
rather than in the language of the machine.rather than in the language of the machine.
--
Precautions to be taken whilePrecautions to be taken whileoverloading operatorsoverloading operators
-
8/7/2019 C++ Presentation 12112007
171/226
overloading operatorsoverloading operators
Do not use tricks when implementingDo not use tricks when implementingoperators. Stick to the acceptedoperators. Stick to the accepted
usage and meaning of the operatorusage and meaning of the operatorin the language.in the language.Do not ever attempt to implement anDo not ever attempt to implement anoverloaded operator withoutoverloaded operator withoutunderstanding the precedence andunderstanding the precedence andassociativity rules.associativity rules.
-
8/7/2019 C++ Presentation 12112007
172/226
Suppose it's needed to have a function thatSuppose it's needed to have a function thatconverts aconverts a
temperature from Fahrenheit to Celsius.temperature from Fahrenheit to Celsius.
-
8/7/2019 C++ Presentation 12112007
173/226
Prototype (Declaration):Prototype (Declaration):void ConvertFToC(float f, float &c);void ConvertFToC(float f, float &c);Definition:Definition:void ConvertFToC(float f, float &c)void ConvertFToC(float f, float &c)
{{ c = (f c = (f - - 32.) * 5./9.;32.) * 5./9.;}}
Now suppose that a Convert function is alsoNow suppose that a Convert function is alsoneeded to convert an integer Fahrenheitneeded to convert an integer Fahrenheit
temperature to Celsius in the same program. Onetemperature to Celsius in the same program. Oneapproach would be to give this function a newapproach would be to give this function a newname, and perhapsname, and perhapsto update the name of the "float" version as wellto update the name of the "float" version as well ..
-
8/7/2019 C++ Presentation 12112007
174/226
void fConvertFToC(float f, float &c);void fConvertFToC(float f, float &c);void iConvertFToC(int f, int &c);void iConvertFToC(int f, int &c);
That's not too bad. There are only two function names toThat's not too bad. There are only two function names tokeepkeeptrack off. Now suppose that a higher precision, double,track off. Now suppose that a higher precision, double,version is needed, or a version for data type short or long.version is needed, or a version for data type short or long.
void fConvertFToC(float f, float &c);void fConvertFToC(float f, float &c);void iConvertFToC(int f, int &c);void iConvertFToC(int f, int &c);void dConvertFToC(double f, double &c);void dConvertFToC(double f, double &c);
void lConvertFToC(long f, long &c);void lConvertFToC(long f, long &c);void sConvertFToC(short f, short &c);void sConvertFToC(short f, short &c);
Virtual F unctionsVirtual F unctionsh i i l b f i ?h i i l b f i ?
-
8/7/2019 C++ Presentation 12112007
175/226
W hat is a "virtual member function"?W hat is a "virtual member function"?-- From an OO perspective, it is the single mostFrom an OO perspective, it is the single mostimportant feature of important feature of
C++. A virtual function allows derived classesC++. A virtual function allows derived classesto replace theto replace the
implementation provided by the base class. Theimplementation provided by the base class. Thecompiler makescompiler makessure the replacement is always called wheneversure the replacement is always called whenever
the object inthe object inquestion is actually of the derived class, even if question is actually of the derived class, even if
the object isthe object isaccessed by a base pointer rather than aaccessed by a base pointer rather than aderived pointer.derived pointer.
-
8/7/2019 C++ Presentation 12112007
176/226
-- This allows algorithms in the base class toThis allows algorithms in the base class tobe replaced in the derived class, even if be replaced in the derived class, even if users don't know about the derived class.users don't know about the derived class.The derived class can either fully replaceThe derived class can either fully replace
("override") the base class member("override") the base class memberfunction, or the derived class can partiallyfunction, or the derived class can partiallyreplace ("augment") the base classreplace ("augment") the base classmember function. The latter ismember function. The latter isaccomplished by having the derived classaccomplished by having the derived classmember function call themember function call the base classbase classmember function, if desired.member function, if desired.
NonNon--virtual member functions are resolved statically. Thatvirtual member functions are resolved statically. Thatis,is,the member function is selected statically (at compilethe member function is selected statically (at compile- -time)time)based on the type of the pointer (or reference) to thebased on the type of the pointer (or reference) to the
-
8/7/2019 C++ Presentation 12112007
177/226
based on the type of the pointer (or reference) to thebased on the type of the pointer (or reference) to theobject.object.I n contrast, virtual member functions are resolvedI n contrast, virtual member functions are resolveddynamicallydynamically(at run(at run- -time). That is, the member function is selectedtime). That is, the member function is selecteddynamically (at rundynamically (at run- -time) based on the type of the object,time) based on the type of the object,notnotthe type of the pointer/reference to that object. This isthe type of the pointer/reference to that object. This iscalledcalled"dynamic binding.""dynamic binding."Most compilers use some variant of the following technique:Most compilers use some variant of the following technique:if if the object has one or more virtual functions, the compilerthe object has one or more virtual functions, the compilerputsputsa hidden pointer in the object called a "virtuala hidden pointer in the object called a "virtual- -pointer" orpointer" or"v"v--pointer." This vpointer." This v- -pointer points to a global table called thepointer points to a global table called the"virtual"virtual- -table" or "vtable" or "v- -table.table. The compiler creates a vThe compiler creates a v- -tabletableforforeach class that has at leasteach class that has at least one virtual function.one virtual function.
Virtual DestructorVirtual Destructor
-
8/7/2019 C++ Presentation 12112007
178/226
-- W hen you may delete a derived object via a base pointerW hen you may delete a derived object via a base pointervirtual functions bind to the code associated with thevirtual functions bind to the code associated with the
class of class of the object, rather than with the class of the pointerthe object, rather than with the class of the pointer
/reference./reference.W hen you say delete basePtr, and the base class has aW hen you say delete basePtr, and the base class has a
virtualvirtualdestructor, the destructor that gets invoked is the onedestructor, the destructor that gets invoked is the oneassociated with the type of the object *basePtr, ratherassociated with the type of the object *basePtr, rather
than thethan theone associated with the type of the pointer.one associated with the type of the pointer.
Let us look at the example given and find out theLet us look at the example given and find out theimportance of declaring the destructor in the Base class asimportance of declaring the destructor in the Base class asvirtual.virtual.
class Base{class Base{public: ~Base() throw(); };public: ~Base() throw(); };
Base::~Base() throw() {Base::~Base() throw() {
-
8/7/2019 C++ Presentation 12112007
179/226
() ()() ()cout
-
8/7/2019 C++ Presentation 12112007
180/226
member function that the basemember function that the baseclass forces derived class to provide.class forces derived class to provide.
These member functionsThese member functionshave no implementation in the basehave no implementation in the base
class.class.Ex: class Shape {Ex: class Shape {
public:public:virtual void draw() =0;};virtual void draw() =0;};
Abstract classAbstract class-- A class that contains atleast one pureA class that contains atleast one purevirtual funtion.virtual funtion.-- The Shape class is an abstract class.The Shape class is an abstract class.
-
8/7/2019 C++ Presentation 12112007
181/226
-
8/7/2019 C++ Presentation 12112007
182/226
C++ Advanced TopicsC++ Advanced Topics
ContentsContents
-
8/7/2019 C++ Presentation 12112007
183/226
Exception H andlingException H andlingTemplatesTemplatesStandard C++ Library ComponentsStandard C++ Library ComponentsStandard Template Library (STL)Standard Template Library (STL)OverviewOverviewReferencesReferences
E xception HandlingE xception Handling
-
8/7/2019 C++ Presentation 12112007
184/226
H ow it is done in CH ow it is done in C
E xception HandlingE xception Handling
-
8/7/2019 C++ Presentation 12112007
185/226
TryTry--catchcatch- -throwthrow trytry -- C++ keyword that denotes anC++ keyword that denotes an
exception blockexception block
catchcatch - - C++ keyword that "catches"C++ keyword that "catches"exceptionsexceptions throwthrow - - C++ keyword that "throws"C++ keyword that "throws"
exceptionsexceptions
-
8/7/2019 C++ Presentation 12112007
186/226
E xception HandlingE xception Handling
-
8/7/2019 C++ Presentation 12112007
187/226
SyntaxSyntaxt ry t ry-- b lo ck b lo ck ::
t ryt ry c ompoun d c ompoun d --s t a t emen t h a n d ler s t a t emen t h a n d ler--lis t lis t
h a n d ler h a n d ler--lis t lis t ::h a n d ler h a n d ler h a n d ler h a n d ler--lis t lis t
optopth a n d ler h a n d ler ::
c a t c hc a t c h (( ex c ep t ionex c ep t ion-- d e c l a r a t iond e c l a r a t ion )) c ompoun d c ompoun d --s t a t emen t s t a t emen t
ex c ep t ionex c ep t ion-- d e c l a r a t iond e c l a r a t ion ::t ypet ype--spe c ifier spe c ifier--lis t d e c l a r a t or lis t d e c l a r a t or t ypet ype--spe c ifier spe c ifier--lis t ab s t r ac t lis t ab s t r ac t -- d e c l a r a t or d e c l a r a t or t ypet ype--spe c ifier spe c ifier--lis t lis t ......
th row th row--expressionexpression ::t hr owt hr ow a ssignmen t a ssignmen t --expressionexpression optopt
E xception HandlingE xception Handling
-
8/7/2019 C++ Presentation 12112007
188/226
H andling of Thrown ExceptionsH andling of Thrown ExceptionsEmpty ThrowsEmpty Throwstry{ throw;}try{ throw;}
Catch All ExceptionsCatch All Exceptionscatch(catch( ) { }) { }
-
8/7/2019 C++ Presentation 12112007
189/226
E xception HandlingE xception Handling
-
8/7/2019 C++ Presentation 12112007
190/226
C++ ExampleC++ Example
-
8/7/2019 C++ Presentation 12112007
191/226
TemplatesTemplates
-
8/7/2019 C++ Presentation 12112007
192/226
Two KindsTwo Kinds Class TemplatesClass Templates
I mplementing class templateI mplementing class templateImplementing class template member
Implementing class template memberfunctionsfunctions
Using class templateUsing class template Function TemplatesFunction Templates
I mplementing template functionsI mplementing template functionsUsing template functionsUsing template functions
Class TemplatesClass Templates
-
8/7/2019 C++ Presentation 12112007
193/226
I mplementing a class templateI mplementing a class templateClass template definition is prefixed by keywordClass template definition is prefixed by keywordtemplate template ExampleExample
I mplementing class template memberI mplementing class template memberfunctionsfunctionsDeclaration and definition in same header fileDeclaration and definition in same header fileExampleExampleExampleExample
Using a class templateUsing a class templateExampleExample I nstantiating a classI nstantiating a class
F unction TemplatesF unction Templates
-
8/7/2019 C++ Presentation 12112007
194/226
I mplementing Template FunctionsI mplementing Template Functions
Using Template FunctionUsing Template Function
-
8/7/2019 C++ Presentation 12112007
195/226
Template S pecializationTemplate S pecialization
-
8/7/2019 C++ Presentation 12112007
196/226
Class template specializationClass template specialization Override the templateOverride the template- -generated codegenerated code
Template Class Partial SpecializationTemplate Class Partial SpecializationFunction template specializationFunction template specialization
NonNon--working exampleworking exampleW orking exampleW orking example
Template ParametersTemplate Parameters
-
8/7/2019 C++ Presentation 12112007
197/226
Default template parameterDefault template parametertemplate Stack { ....} ;
S tatic M embers and VariablesS tatic M embers and Variables
-
8/7/2019 C++ Presentation 12112007
198/226
Each template class or functionEach template class or functiongenerated from a template has itsgenerated from a template has itsown copies of any static variables orown copies of any static variables or
membersmembers
Templates and F riendsTemplates and F riends
-
8/7/2019 C++ Presentation 12112007
199/226
C la ss T em p la t eC la ss T em p la t e frie n d de c lara t ion in c la ssfrie n d de c lara t ion in c la sst em p la t e Xt em p la t e X
R e su lts o f g iv ing frie n d s hi pR e su lts o f g iv ing frie n d s hi p
template class class Xtemplate class class X friend void f1() ;friend void f1() ; makes f1() a friend of all instantiations of makes f1() a friend of all instantiations of template X. For example, f1() is a friend of template X. For example, f1() is a friend of X, X, and X.X, X, and X.
template class class Xtemplate class class X friend void f2(X&) ;friend void f2(X&) ; For a particular type T for example, float,For a particular type T for example, float,
makes f2(X&) a friend of classmakes f2(X&) a friend of classX only. f2(x&) cannot be aX only. f2(x&) cannot be afriend of class X.friend of class X.
template class class Xtemplate class class X friend A::f4() ; // A is a userfriend A::f4() ; // A is a userdefined class with a memberdefined class with a memberfunction f4() ;function f4() ;
makes A::f4() a friend of all instantiations of makes A::f4() a friend of all instantiations of template X. For example, A::f4() is a friendtemplate X. For example, A::f4() is a friendof X, X, and X.of X, X, and X.
template class class Xtemplate class class X friend C::f5(X&) ; // C isfriend C::f5(X&) ; // C isa class template with a membera class template with a member
function f5function f5
For a particular type T for example, float,For a particular type T for example, float,makes C::f5(X&) a friend of makes C::f5(X&) a friend of
class X only.class X only.C::f5(x&) cannot be a friendC::f5(x&) cannot be a friendof class X.of class X.
template class class Xtemplate class class X friend class Y ;friend class Y ; makes every member function of class Y amakes every member function of class Y afriend of every template class produced fromfriend of every template class produced fromthe class template X.the class template X.
template class class Xtemplate class class X friend class Z ;friend class Z ; when a template class is instantiated with awhen a template class is instantiated with aparticular type T, such as a float, allparticular type T, such as a float, allmembers of class Z become friendsmembers of class Z become friends
S tandard C++ LibraryS tandard C++ Library
-
8/7/2019 C++ Presentation 12112007
200/226
Main ComponentsMain Components The Standard Template Library (STL)The Standard Template Library (STL) The I ostream LibraryThe I ostream Library The String ClassesThe String Classes UtilitiesUtilities LocalizationLocalization The Numerics LibraryThe Numerics Library Language SupportLanguage Support The Standard C LibraryThe Standard C Library
S TL O verviewS TL O verview
-
8/7/2019 C++ Presentation 12112007
201/226
ContainersContainersI teratorsI teratorsAlgorithmsAlgorithmsFunction ObjectsFunction ObjectsAdaptorsAdaptorsAllocatorsAllocators
ContainersContainers
-
8/7/2019 C++ Presentation 12112007
202/226
SequencesSequencesVectorsVectorsListsListsDequesDeques
Stacks and QueuesStacks and QueuesAssociative containersAssociative containers
SetsSetsMultisetsMultisetsMapsMapsMultimapsMultimaps
Iterators and F unction O bjectsIterators and F unction O bjects
-
8/7/2019 C++ Presentation 12112007
203/226
I teratorsI teratorsI nputI nputOutputOutputForwardForwardBidirectionalBidirectionalRandom accessRandom access
Function ObjectsFunction ObjectsGeneratorsGeneratorsPredicatesPredicates
S TLS TL
-
8/7/2019 C++ Presentation 12112007
204/226
CmapCmapListListVectorVectorDeDe--QueueQueue
CmapCmap
-
8/7/2019 C++ Presentation 12112007
205/226
CMapCMap Constructs a collection that mapsConstructs a collection that mapskeys to values.keys to values.
O p era t ionsO p era t ions
GetH
ashTableSizeGetH
ashTableSize Returns the sizeReturns the size(number of elements) of the hash table.(number of elements) of the hash table.GetNextAssocGetNextAssoc Gets the next element forGets the next element foriterating.iterating.
PGetNextAssocPGetNextAssoc Gets a pointer to the nextGets a pointer to the nextelement for iterating.element for iterating.
cmapcmap
-
8/7/2019 C++ Presentation 12112007
206/226
GetStartPositionGetStartPosition Returns the position of theReturns the position of thefirst element.first element.PGetFirstAssocPGetFirstAssoc Returns a pointer to theReturns a pointer to thefirst element.first element.I nit H ashTableI nit H ashTable I nitializes the hash table andI nitializes the hash table andspecifies its size.specifies its size.LookupLookup Looks up the value mapped to aLooks up the value mapped to agiven key.given key.PLookupPLookup Returns a pointer to a key whoseReturns a pointer to a key whosevalue matches the specified value.value matches the specified value.operator []operator [] I nserts an element into theI nserts an element into themapmap operator substitution foroperator substitution for S e tAtS e tAt ..
CM apCM ap
-
8/7/2019 C++ Presentation 12112007
207/226
RemoveAllRemoveAll Removes all the elements fromRemoves all the elements fromthis map.this map.RemoveKeyRemoveKey Removes an element specifiedRemoves an element specifiedby a key.by a key.
SetAtSetAt I nserts an element into the map;I nserts an element into the map;replaces an existing element if a matchingreplaces an existing element if a matchingkey is found.key is found.
S t a tusS t a tus
GetCountGetCount Returns the number of elementsReturns the number of elementsin this map.in this map.GetSizeGetSize Returns the number of elements inReturns the number of elements inthis map.this map.
cmapcmap
-
8/7/2019 C++ Presentation 12112007
208/226
I sEmptyI sEmpty Tests for the emptyTests for the empty- -mapmapcondition (no elements).condition (no elements).
D a t a Mem b er sD a t a Mem b er s
CMap::CPairCMap::CPair A nested structureA nested structurecontaining a key value and the valuecontaining a key value and the valueof the associated objectof the associated object
vector vector
-
8/7/2019 C++ Presentation 12112007
209/226
ConstructorsConstructors v e c to rv e c to rC onst r u c ts a v e c to r o f a sp e c ifi c s ize C onst r u c ts a v e c to r o f a sp e c ifi c s ize o r w it h eleme nts o f a sp e c ifi c v al u e o r o r w it h eleme nts o f a sp e c ifi c v al u e o r w it h a sp e c ifi c all o c a to r o r a s a c op y w it h a sp e c ifi c all o c a to r o r a s a c op y
o f so me ot her v e c to r.o f so me ot her v e c to r.TypedefsTypedefs all o c a to r_ t y p eall o c a to r_ t y p eA t y p e t ha t re p re s e nts t he all o c a to r A t y p e t ha t re p re s e nts t he all o c a to r c la ss f o r t he v e c to r obj e c t .c la ss f o r t he v e c to r obj e c t .c onst _i t era to rc onst _i t era to rA t y p e t ha t p r ov ide s a ra n d o mA t y p e t ha t p r ov ide s a ra n d o m--a cc e ssa cc e ssit era to r t ha t c a n read a c onst eleme ntit era to r t ha t c a n read a c onst eleme ntin a v e c to r.in a v e c to r.
vector vector
-
8/7/2019 C++ Presentation 12112007
210/226
c onst _ po int erc onst _ po int erA t y p e t ha t p r ov ide s a po int er to a A t y p e t ha t p r ov ide s a po int er to a c onst eleme nt in a v e c to r.c onst eleme nt in a v e c to r.c onst _refere n c ec onst _refere n c eA t y p e t ha t p r ov ide s a refere n c e to a A t y p e t ha t p r ov ide s a refere n c e to a c onst eleme nt sto red in a v e c to r f o r c onst eleme nt sto red in a v e c to r f o r readi ng a n d p erf o rmi ng c onstreadi ng a n d p erf o rmi ng c onstop era t ions .op era t ions .c onst _re v er s e_i t era to rc onst _re v er s e_i t era to rA t y p e t ha t p r ov ide s a ra n d o mA t y p e t ha t p r ov ide s a ra n d o m--a cc e ssa cc e ssit era to r t ha t c a n read a n y c onstit era to r t ha t c a n read a n y c onsteleme nt in t he v e c to r.eleme nt in t he v e c to r.
vector vector
-
8/7/2019 C++ Presentation 12112007
211/226
differe n c e_ t y p ediffere n c e_ t y p eA t y p e t ha t p r ov ide s t he differe n c e A t y p e t ha t p r ov ide s t he differe n c e b e tw ee n t he addre ss e s o f twob e tw ee n t he addre ss e s o f twoeleme nts in a v e c to r.eleme nts in a v e c to r.
it era to rit era to rA t y p e t ha t p r ov ide s a ra n d o mA t y p e t ha t p r ov ide s a ra n d o m--a cc e ssa cc e ssit era to r t ha t c a n read o r m o dify a n y it era to r t ha t c a n read o r m o dify a n y eleme nt in a v e c to r.eleme nt in a v e c to r.
po int erpo int erA t y p e t ha t p r ov ide s a po int er to a nA t y p e t ha t p r ov ide s a po int er to a neleme nt in a v e c to r.eleme nt in a v e c to r.
vector vector
-
8/7/2019 C++ Presentation 12112007
212/226
refere n c erefere n c eA t y p e t ha t p r ov ide s a refere n c e to a nA t y p e t ha t p r ov ide s a refere n c e to a neleme nt sto red in a v e c to r.eleme nt sto red in a v e c to r.re v er s e_i t era to rre v er s e_i t era to rA t y p e t ha t p r ov ide s a ra n d o mA t y p e t ha t p r ov ide s a ra n d o m--a cc e ssa cc e ssit era to r t ha t c a n read o r m o dify a n y it era to r t ha t c a n read o r m o dify a n y eleme nt in a re v er s ed v e c to r.eleme nt in a re v er s ed v e c to r.s ize_ t y p es ize_ t y p eA t y p e t ha t c ounts t he nu m b er o f A t y p e t ha t c ounts t he nu m b er o f eleme nts in a v e c to r.eleme nts in a v e c to r.v al u e_ t y p ev al u e_ t y p eA t y p e t ha t re p re s e nts t he da t a t y p e A t y p e t ha t re p re s e nts t he da t a t y p e
vector vector
-
8/7/2019 C++ Presentation 12112007
213/226
Member FunctionsMember Functions a ss igna ss ignE ra s e s a v e c to r a n d c op ie s t he E ra s e s a v e c to r a n d c op ie s t he sp e c ified eleme nts to t he em pt y sp e c ified eleme nts to t he em pt y v e c to r.v e c to r.
a ta tR e tu r ns a refere n c e to t he eleme nt a tR e tu r ns a refere n c e to t he eleme nt a ta sp e c ified lo c a t ion in t he v e c to r.a sp e c ified lo c a t ion in t he v e c to r.b a ckb a ckR e tu r ns a refere n c e to t he la stR e tu r ns a refere n c e to t he la steleme nt o f t he v e c to r.eleme nt o f t he v e c to r.b e g inb e g inR e tu r ns a ra n d o mR e tu r ns a ra n d o m--a cc e ss it era to r toa cc e ss it era to r to
vector vector
-
8/7/2019 C++ Presentation 12112007
214/226
c a p a c it yc a p a c it yR e tu r ns t he nu m b er o f eleme nts t ha tR e tu r ns t he nu m b er o f eleme nts t ha tt he v e c to r c ou ld c ont ai n w it h outt he v e c to r c ou ld c ont ai n w it h outall o c a t ing m o re sto ra g e.all o c a t ing m o re sto ra g e.c learc learE ra s e s t he eleme nts o f t he v e c to r.E ra s e s t he eleme nts o f t he v e c to r.em pt yem pt yTe sts if t he v e c to r c ont ai n er is em pt y.Te sts if t he v e c to r c ont ai n er is em pt y.e n de n dR e tu r ns a ra n d o mR e tu r ns a ra n d o m--a cc e ss it era to r t ha ta cc e ss it era to r t ha tpo ints just b ey on d t he e n d o f t he po ints just b ey on d t he e n d o f t he v e c to r.v e c to r.
vector vector
-
8/7/2019 C++ Presentation 12112007
215/226
era s eera s eR em ov e s a n eleme nt o r a ra ng e o f R em ov e s a n eleme nt o r a ra ng e o f eleme nts in a v e c to r fr o m sp e c ified eleme nts in a v e c to r fr o m sp e c ified pos it ions .pos it ions .
fr ontfr ontR e tu r ns a refere n c e to t he fir stR e tu r ns a refere n c e to t he fir steleme nt in a v e c to r.eleme nt in a v e c to r.g e t _all o c a to rg e t _all o c a to rR e tu r ns a n obj e c t to t he all o c a to r R e tu r ns a n obj e c t to t he all o c a to r c la ss us ed b y a v e c to r.c la ss us ed b y a v e c to r.ins er tins er tIns er ts a n eleme nt o r a nu m b er o f Ins er ts a n eleme nt o r a nu m b er o f
vector vector
-
8/7/2019 C++ Presentation 12112007
216/226
max_ s izemax_ s izeR e tu r ns t he maxim u m le ngt h o f t he R e tu r ns t he maxim u m le ngt h o f t he v e c to r.v e c to r.pop _ b a ckpop _ b a ckD ele t e s t he eleme nt a t t he e n d o f t he D ele t e s t he eleme nt a t t he e n d o f t he v e c to r.v e c to r.pus h_ b a ckpus h_ b a ckAdd a n eleme nt to t he e n d o f t he Add a n eleme nt to t he e n d o f t he v e c to r.v e c to r.r b e g inr b e g inR e tu r ns a n it era to r to t he fir stR e tu r ns a n it era to r to t he fir steleme nt in a re v er s ed v e c to r.eleme nt in a re v er s ed v e c to r.
vector vector
-
8/7/2019 C++ Presentation 12112007
217/226
re n dre n dR e tu r ns a n it era to r to t he e n d o f a R e tu r ns a n it era to r to t he e n d o f a re v er s ed v e c to r.re v er s ed v e c to r.re s izere s izeS p e c ifie s a n e w s ize f o r a v e c to r.S p e c ifie s a n e w s ize f o r a v e c to r.re s er v ere s er v eR e s er v e s a mi n im u m le ngt h o f R e s er v e s a mi n im u m le ngt h o f sto ra g e f o r a v e c to r obj e c t .sto ra g e f o r a v e c to r obj e c t .s izes izeR e tu r ns t he nu m b er o f eleme nts inR e tu r ns t he nu m b er o f eleme nts int he v e c to r.t he v e c to r.
vector vector
-
8/7/2019 C++ Presentation 12112007
218/226
sw a psw a pE x c ha ng e s t he eleme nts o f twoE x c ha ng e s t he eleme nts o f twov e c to r s .v e c to r s .
OperatorsOperators op era to r[]op era to r[]R e tu r ns a refere n c e to t he v e c to r R e tu r ns a refere n c e to t he v e c to r eleme nt a t a sp e c ified pos it ioneleme nt a t a sp e c ified pos it ion
M akefileM akefile
-
8/7/2019 C++ Presentation 12112007
219/226
ma k efile c ont ai nsma k efile c ont ai ns D e s c ri pt ion b lo ck sD e s c ri pt ion b lo ck sTar g e tsTar g e tsD e p e n de ntsD e p e n de nts
C o mma n d sC o mma n d sproject.obj : project.c project.h ; cl /c project.cproject.obj : project.c project.h ; cl /c project.c
Ma c r osMa c r os
In fere n c e r u le sIn fere n c e r u le sD ot dire c t iv e sD ot dire c t iv e sP re p r o c e ss ing dire c t iv e sP re p r o c e ss ing dire c t iv e s
M akefileM akefile
-
8/7/2019 C++ Presentation 12112007
220/226
Coding S tandardsCoding S tandards
-
8/7/2019 C++ Presentation 12112007
221/226
F ollow these standards even if your way is better F ollow the naming conventions
F ollow the formatting and commenting conventions
Avoid the preprocessor Do not use magic numbersDo not use global variablesKnow how to use runtime static initializationDo not use data members to record type
Coding S tandardsCoding S tandards
-
8/7/2019 C++ Presentation 12112007
222/226
Do not castDo not cast away constAvoid problems with object slicing and
temporariesMake all data members privateDo not use inline virtual functions
Coding S tandardsCoding S tandards
-
8/7/2019 C++ Presentation 12112007
223/226
L ocate the deletion corresponding to everyallocationKnow who owns the elements of a collection
Make ownership clear Redesign rather than just copying and pastingUse virtual functions in preference to switches
and other conditional code
Coding S tandardsCoding S tandards
-
8/7/2019 C++ Presentation 12112007
224/226
Do not use anachronismsWrap platform-specific codeConsider tomorrow's changes when coding
todayYou are responsible for understanding and
applying these standards If you don't
understand one of the items above, ask about itbefore you write any more code
-
8/7/2019 C++ Presentation 12112007
225/226
-
8/7/2019 C++ Presentation 12112007
226/226
Thank YouThank You