1 01jun00 17jul00 01jul03
14 // Constructors, Destructors
15 Pet(): weight(1), food("Pet Chow") {}
19 void setWeight(int w) {weight = w;}
20 int getWeight() {return weight;}
22 void setfood(string f) {food = f;}
23 string getFood() {return food;}
37 cout << "Eating " << food << endl;
42 cout << "Growl" << endl;
52 void sicken() {cout << "Speading Plague" << endl;}
59 Cat() : numberToes(5) {}
63 void setNumberToes(int toes) {numberToes = toes;}
64 int getNumberToes() {return numberToes;}
75 charles.setWeight(25);
76 cout << "Charles weighs " << charles.getWeight() << " lbs. " << endl;
83 cout << "Fluffy has " << fluffy.getNumberToes() << " toes " << endl;
90 Output of code example {{{2
92 Charles weighs 25 lbs.
104 Possible to "clone" existing class to new one with exception that if the original class
105 called base (or super or parent ) is changed,the modified "clone" ( called derived or
106 inherited or child or sub ) also reflect those changes.
107 To change the derived class possible by adding new member funcs or by changing
108 existing funcs ( called override ).
109 If the derived class only override base class funcs ( and not to add new ) so
110 because the interface will be the same will have almost the same class type.
111 As a result possible to substitute object of the derived class with object of the base
112 class. This substitution principle called pure substitution.
113 Adding new func to the derived class creating follow situation:
114 This will expend interface but this new type will still be substitute for the base class,
115 but substitution isn't perfect cause the new func doesn't accessible from base type.
119 Operator overloading{{{
121 Only existing operators can be overloaded.
125 run time type info (rtti) {{{1
132 Composition(Aggregation)
133 Can put object of existing class as member of another class (creating member object).
134 Also called "has-a" relationship.
136 4 Interchangeable objects with polymorphism
137 To write code that doesn't depent on specific type needs to treat object as its base
138 type. The problem is that compiler can not know what code will be executed. The
139 answer is that compiler change traditional call.
140 The non-OOP compilers generates func call called early binding ( compiler generate
141 call to func name and linker resolve it to absolute address ). In OOP address of call
142 can not be determine until runtime. The OOP compiler using late binding where
143 compiler does ensure that func exists and perform type checking on args and
144 return value. Actualy compiler place specified bit of code instead of address in place
146 The proccess of treating a derived type as base type called upcasting.
148 5 Creating and destroying objs
149 For max runtime speed, the storage and lifetime can be determined while the program
150 is being writen by placing the objs on the stack or in static storage.
151 Stack memory used directly by CPU to store data during program execution. Vars at
152 stack called automatic ( or scoped ). The static storage simply patch of memory before
153 the program begins to run.
154 Possible to create objs dynamically in heap, using new keyword. In that you don't know
155 how many objs you need, what there lifetime and what their exact type is. When you
156 finish w/ storage must release using delete keyword.
157 Because the heap storage managed dynamically at runtime, the amount of time
158 required to allocate storage on the heap longer than to create storage on the stack.
159 The lifetime of obj. If you create obj on stack or static storage the compiler determine
160 how much obj will be alive and automatically destroyed it. When create obj at heap the
161 compiler doesn't know about them so programmer have to delete them. Additional
162 exists feature called garbage collector.
164 6 Declaration vs. Definition
165 A declaration introduces a name - an identifier - to the compiler. It says to compiler
166 "this func or var exists somewhere and here is what it is should look like.
167 A definition says: "Make this var here". It allocates storage for the name and in the point
168 of definition allocates storage. ???
170 7 Funcs declaration and definition
171 int func1( int len1,int len2)
172 Arguments in declaration may have names, but compiler ignores them. The func decla-
173 ration w/o args int func2() gives in C meaning of func w/ any number and type of args and
174 in C++ func w/o args. Definition looks like declaration but have a body.
176 8 Var declaration and definition
177 extern int i; // declaration w/o definition
178 extern float f(float); // func declaration
180 float b; // declaration & definition
181 float f(float a) { // definition
186 int h(int x) { // declaration & definition
198 The librarys inherired from C still available in traditional ".h" extension, but possible
199 to use them in C++ style by prepending a "c" before the name, like instead of
200 #include <stdlib.h> will be #include <cstdlib>
201 The difference is that using header w/ ".h" gives older non-template version of header
202 file and w/o ".h" gives new template version. Problem to mix them.
205 When linker found external reference to a func or a var : if it not already encountered
206 definition it adds identifier to its list of "unresolved references" oposite the reference
208 First linker search in objs and if not find start search at libraries. Libraries have some
209 sort of indexing so linker looking for the library obj that contents definition of reference
210 and linked it to executable ( only the obj that content definition not whole library ).
211 If want to minimize exe file just put single funs in each source code file when build
213 Because linker searches files in order you give them , possible to pre-empt the use
214 of a library func by inserting a file w/ your own func, using the same func name, into
215 the list before library name appears. So linker would find the definition from your file
216 before going to library.
217 There are additional items added to exe file in linking. One of them is startup module,
218 contents init routines that must be run any time a C/C++ program executed. These
219 routines set up stack and init certain vars.
220 Linker searches "standard" funcs in standard library, so just add header file for
221 certain funs. In case of add-on library needs to add library filename to linker.
224 To prevent colisions of func or var name C++ have keyword namespace.
225 Each set of C++ definitions in library or program "wrapped" in a namespace,
226 so if other definition has identical name in a different namespace - no colision.
227 Foolow code should be use:
229 This is expose all names from namespace, but only those for current file.
231 12 Introducing strings, read and write files, vector
232 String manipulation simple case of string class exists in C++.
242 cout << s1 + s2 + "!" << endl;
246 To open file just add <fstream>. This is automatically include <iostream>.
247 So to open file for reading creates obj fstream that behaves like cin and for
248 open writing obj ofstream behaves like cout.
249 There is func getline() which reads one line (terminated by newline) from ifstream.
250 This is example to copy one file into another:
255 ifstream in("Scopy.cpp"); // open for read
256 ofstream out("Scopy2.cpp"); // open for write
258 while(getline(in,s)) // newline discard and not copy to s
261 Another example is copy whole file into string:
268 ifstream in("Scopy.cpp"); // open for read
270 while(getline(in,line)) // newline discard and not copy to s
275 In case of reading file into string obj problem to know how many string objs
276 needs cause this will known only after reading whole file.
277 The class vector solved it. This is template ,means, can be applied to different
278 types, like vector of strings: vector<string>
279 It's also content all array behavior.Example of reading file and add line numbers:
288 ifstream in("Scopy.cpp"); // open for read
290 while(getline(in,line)) // newline discard and not copy to s
291 v.push_back(line); // add line to the end
292 for( int i=0; i< v.size() ; i++) // i less than number of elements of v
293 cout << i << ": " << v[i] << endl;
295 There is example how to break a file into whitespace-separated words:
304 ifstream in("Scopy.cpp"); // open for read
306 while( in >> word) // gets one word at a time
307 v.push_back(word); // add line to the end
308 for( int i=0; i< v.size() ; i++) // i less than number of elements of v
309 cout << v[i] << endl;
319 declaration prototype: float func(float ,float, float);
321 Controlling execution
327 cout <<"type number"<<endl;
329 if(i>5) cout << "greater than 5" << endl;
330 else if (i=5) cout << "equal to 5" << endl;
331 else cout << "less tyhan 5" << endl;
341 while( guess != secret )
342 cout << "guess number:";
345 cout << "Right!!!" << endl;
347 Do-while , For , Break and Continue
354 cout << "main menu:" << endl;
355 cout << "l: left; q: quit; -> ";
357 if (c == 'q') break; // out of while
359 cout << "Left menu:" << endl;
360 cout << "Slect a or b";
363 cout << "Choosen 'a'" << endl;
364 continue; // Back to Main Menu
367 cout << "Choosen 'b'" << endl;
368 continue: // back to Main Menu
371 cout << "Wrong choose" << endl;
372 continue; // back to Main Menu
375 cout << "Must choose l or q" << endl;
377 cout << "quiting . . ." << endl
381 case integral_value1: statement; break;
385 It's requires a selector that evaluates to an integral value
386 at compile time, so string object as a selector won't work.
391 void removeHat(char cat) {
392 for (char c = 'A'; c < cat; c++)
395 cout << "cat " << cat << endl;
398 else cuot << "Voom!!!" << endl;
405 Introduction to data types
407 There are 4 basic data types: int , char , float , double.
408 Bool , true and false.
409 The standard C++ bool type have two states by the built-in constants true
410 ( integral one) and false ( integral zdero ). Compiler will implicitly convert
411 from an int to a bool ( nonzero values will produce true ).
412 The use of ++ (increment) to set a flag to true still allowed but deprecated.
413 The problem is that it's making implicit type conversion from bool to int,
414 incrementing the value and then implicitly converting it back again.
416 They modifies meaning of basic types by expanding them.
417 here are 4: long , short , signed , unsigned.
419 Every part of program have it location in memory, so we can get address
420 of that place. The operator & gives this possibily.
427 cuot << "Pet id:" << pet << endl;
433 cout << "f() " << (long)&f << endl;
434 cout << "dog: " << (long)&dog << endl;
435 cout << "i: " << (long)&i << endl;
438 By results possible to see that vars defined in main() are in different area
439 than the vars defined outside main().
440 Modifying outside obj.
445 cout << "*p = " << *p << endl;
447 cout << "*p = " << *p << endl;
452 cout << "x = " << x << endl;
454 cout << "x = " << x << endl;
456 Intro to C++ references.
457 Additional way to pass an address into a func is reference.
458 Changed last program to pass by reference.
463 cout << "&p = " << &p << endl;
465 cout << "&p = " << &p << endl;
470 cout << "x = " << x << endl;
471 f(x); // looks like pass-by-value but it's pass-by-reference
472 cout << "x = " << x << endl;
474 Pointer and reference as modifiers
475 All possible ombinations of basic data types , spicifiers, pointers and
477 void f1(char c,int i,float f, double d);
478 void f2(short int si, long int li, long double ld);
479 void f3(unsigned char uc,unsigned int ui,unsigned short int usi,
480 unsigned long int uli);
481 void f4(char* cp,int* ip,float* fp, double* dp);
482 void f5(short int* sip, long int* lip, long double* ldp);
484 Pointer to void type means that it is pointer to any data type.
485 There is no reference to void.
488 Scope of var extends from the point it defined to the first closing brace.So a scope is defined by its "nearest" set of braces.
489 Defining vars on the fly.
490 C++ gives to define var anywhere in a scopeeven right before use. Possible to define var inside the control expressions of for and while loops,inside the conditional of an if
491 statement and inside the selector statement of a switch.
493 Specifying storage allocation
495 Defines outside all function bodies and are available to all parts of the
496 program even in other files. If existence of a global var in one file is
497 declared using the extern keyword ni other file , the data is available for
507 cout << globe << endl;
509 cout << globe << endl;
518 Because global2.cpp compiled separately from global.cpp compile must be informed that the var exists by declaration.
520 Those vars "local" to a func.They are often called "automatic" cause they automaticly come into being when the scope entered and go away when the scope closes. The keyword auto makes this explicit, but local vars default to auto so it's never necessary to declare. The register keyword tells the compiler "make access to this var as fast as possible".The restrictions is - can't take or compute the address of register var.
521 Can't have global or static register var.
523 Often var declared in scope of func disappear at the end of the func scope. So every
524 executing of func will create new vars and values are reinitialized. If you want a vlaue to be extant throughout the life of a program needs to define local var w/ keyword static and give
525 it an initial value. The initialization is perfomed only the first timethe func is called and the data remains value between func calls. The static var is not accessable out of func scope. When static used w/ func name or var declared outside of any func scope it's mean - That name is unavailable outside of this file.It file scope.
527 This will tell to compiler that the definition exists somewhere as a global var.If put static before extern will cause to linker error.
529 Every identifier is represented by storage in memory that holds a var or a compiled func body. There are two types of linkage: internal and external.
530 Internal : the storage created is created to represent identifier only for the file being compiled.Other files may use the same identifier name with internal linkage or for a global var and will be no conflicts.Internal linkage is specified by keyword static.
531 External : the storage created to represent the identifier for all file being compiled.
532 The storage created once and linker must resolve all other references to that storage. Global vars and funcs name have external linkage.
535 C++ concept of a named constant is just like a var, except that its value cann't be changed.
536 The modifier const tells compiler that a name represents a constant.
537 The constant must always have initialization value.Values w/o type assumes as decimal. Constant w/ leading 0 treated as octal; w/ 0x treated as hex.Possible to add suffixes to force the type of floating-point number: f or F - a float; l or L - long double, otherwise will be double.
538 Char constnts are chars surrounded by single quotes. Special chars represented w/ backslash.
539 \n - new line; \t - tab; \\ - backslash; \r - carriage return; \" - double quotes; \' - single quote.
540 Also char const in octal - '\17' or hex - '\xff'.
543 Prevent compiler from optimizing certain var or const.
547 Operator = where right-hand side ( calld rvalue ) copy to left-hand side ( lvalue ).
550 + addition - substraction / division * multiplication % modulus
551 % - produces reminder from integer division ( can't use float-point numbers. )
554 Establish a relationship between the values of the operands and produce a Boolean,
559 Operators and ( && ) and or ( || ) produce true or false.Statement true if it has non-zero
563 Manipulate w/ individual bits. Works only w/ integral types char , int , long.
564 The bitwise and ( & ) produce 1 if both input bits are 1, otherwise 0.
565 The bitwise or ( | ) produce 0 if both input bits are 0 ,otherwise 1.
566 The bitwise exclusive or ( ^ ) produce 1 if one of input bits 1 ,but not both.
567 The bitwise not ( ~ ) produce opposite of the input bit.
570 The left-shift ( << ) produces the operand to the left of the operator shifted to the left by the
571 number of bits specified after the operator.
572 The right-shift ( >> ) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator.
573 Example func displays single byte bit-by-bit
574 void printByte( const unsigned char val)
575 for ( i = 7; i >= 0 ; i--) {
576 if( val & ( 1 << i ) )
583 Bitwise not ( ~ ), logical not ( ! ), minus( - ), plus ( + ), increment and decrement ( ++ -- ),
584 address-of ( & ), dereference ( * -> ), cast operator and new and delete in C++.
587 The operator if-else and conditional operator ( ? ).
590 The ( , ) operator used to separate expressions.For example multipile definitions:
592 and increment list of vars and uses the last one as rvalue:
593 a = (b++,c++,d++,e++);
596 Additional cast syntax:
597 float a = float(200)l;
598 float b = (float)200;
599 Explicit C++ cast syntax:
609 Composite type creation
610 First is typedef that is alias to existing type. In case
612 would be int* which is x and int which is y.
614 In C this simple associating integral values w/ names, but in C++ it's also type checking.
615 Actualy in C++ creates a new type and name of enumaration becomes reserved word.
616 In addition in C++ type checking of enum stricker.In C you can do with instance a of
617 enumaration color like a++ but in C++ can't , cause it's contents 2 type conversions.
618 From color to int ( permited in C++ ) and back that is forbidden.
619 The next is union.Puts all data into a single space; it's figures out the amount of space
620 necessary for the lagest item of union.
621 Next is arrays.Method to pack data together but nice dynamical array in C. In C++ there
622 is vector object that auto-resides itself.