Cheat Sheet of C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

1

2
3 // Tells the compiler iostream library which contains the function cout
4 #include <iostream>
5
6 // Allows us to use vectors
7 #include <vector>
8
9 // Allows us to use strings
10 #include <string>
11
12 // Allow us to work with files
13 #include <fstream>
14
15 // Allows functions in the std namespace to be used without their prefix
16 // std::cout becomes cout
17 using namespace std;
18
19 // ---------- FUNCTIONS ----------
20 // The function has return type, function name and attributes with
21 // their data types
22 // The attribute data types must match the value passed in
23 // This data is passed by value
24 // You can define default values to attributes as long as they come last
25 // This is known as a function prototype
26 int addNumbers(int firstNum, int secondNum = 0){
27
28 int combinedValue = firstNum + secondNum;
29
30 return combinedValue;
31
32 }
33
34 // An overloaded function has the same name, but different attributes
35 int addNumbers(int firstNum, int secondNum, int thirdNum){
36
37 return firstNum + secondNum + thirdNum;
38
39 }
40
41 // A recursive function is one that calls itself
42
43 int getFactorial(int number){
44
45 int sum;
46 if(number == 1) sum = 1;
47 else sum = (getFactorial(number - 1) * number);
48 return sum;
49
50 // getFactorial(2) [Returns 2] * 3
51 // getFactorial(1) [Returns 1] * 2 <This value goes above>
52 // 2 * 3 = 6
53
54 }
55
56 // Doesn't have a return type so use void
57 // Since I'm getting a pointer use int*
58 // Refer to the referenced variable with *age
59 void makeMeYoung(int* age){
60
61 cout << "I used to be " << *age << endl;
62 *age = 21;
63
64 }
65
66 // A function that receives a reference can manipulate the value globally
67 void actYourAge(int& age){
68
69 age = 39;
70
71 }
72
73 // ---------- END OF FUNCTIONS ----------
74
75 // ---------- CLASSES ----------
76 // classes start with the name class
77
78 class Animal
79 {
80
81 // private variables are only available to methods in the class
82 private:
83 int height;
84 int weight;
85 string name;
86
87 // A static variable shares the same value with every object in the class
88 static int numOfAnimals;
89
90 // Public variables can be accessed by anything with access to the object
91 public:
92 int getHeight(){return height;}
93 int getWeight(){return weight;}
94 string getName(){return name;}
95 void setHeight(int cm){ height = cm; }
96 void setWeight(int kg){ weight = kg; }
97 void setName(string dogName){ name = dogName; }
98
99 // Declared as a prototype
100 void setAll(int, int, string);
101
102 // Declare the constructor
103 Animal(int, int, string);
104
105 // Declare the deconstructor
106 ~Animal();
107
108 // An overloaded constructor called when no data is passed
109 Animal();
110
111 // protected members are available to members of the same class and
112 // sub classes
113
114 // Static methods aren't attached to an object and can only access
115 // static member variables
116 static int getNumOfAnimals() { return numOfAnimals; }
117
118 // This method will be overwritten in Dog
119 void toString();
120
121 };
122
123 int Animal::numOfAnimals = 0;
124
125 // Define the protoype method setAll
126 void Animal::setAll(int height, int weight, string name){
127
128 // This is used to refer to an object created of this class type
129 this -> height = height;
130 this -> weight = weight;
131 this -> name = name;
132 Animal::numOfAnimals++;
133
134 }
135
136 // A constructor is called when an object is created
137 Animal::Animal(int height, int weight, string name) {
138
139 this -> height = height;
140 this -> weight = weight;
141 this -> name = name;
142
143 }
144
145 // The destructor is called when an object is destroyed
146 Animal::~Animal() {
147
148 cout << "Animal " << this -> name << " destroyed" << endl;
149
150 }
151
152 // A constructor called when no attributes are passed
153 Animal::Animal() {
154 numOfAnimals++;
155 }
156
157 // This method prints object info to screen and will be overwritten
158 void Animal::toString(){
159
160 cout << this -> name << " is " << this -> height << " cms tall and "
161 << this -> weight << " kgs in weight" << endl;
162
163 }
164
165 // We can inherit the variables and methods of other classes
166 class Dog : public Animal{
167
168 private:
169 string sound = "Woof";
170 public:
171 void getSound() { cout << sound << endl; }
172
173 // Declare the constructor
174 Dog(int, int, string, string);
175
176 // Declare the default constructor and call the default superclass
177 // constructor
178 Dog() : Animal(){};
179
180 // Overwrite toString
181 void toString();
182
183 };
184
185 // Dog constructor passes the right attributes to the superclass
186 // constructor and then handles the attribute bark that remains
187 Dog::Dog(int height, int weight, string name, string bark) :
188 Animal(height, weight, name){
189
190 this -> sound = bark;
191
192 }
193
194 // toString method overwritten
195 void Dog::toString(){
196
197 // Because the attributes were private in Animal they must be retrieved
198 // by called the get methods
199 cout << this -> getName() << " is " << this -> getHeight() <<
200 " cms tall and " << this -> getWeight() << " kgs in weight and says " <<
201 this -> sound << endl;
202
203 }
204
205 // ---------- END OF CLASSES ----------
206
207 // This is where execution begins. Attributes can be sent to main
208 int main() {
209
210 // cout outputs text and a carriage return with endl
211 // Statements must end with a semicolon
212 // Strings must be surrounded by "
213 // << sends the text via standard output to the screen
214 cout << "Hello Internet" << endl;
215
216 // ---------- VARIABLES / DATA TYPES ----------
217 // Variables start with a letter and can contain letters, numbers and _
218 // They are case sensitive
219
220 // A value that won't change is a constant
221 // Starts with const and it should be uppercase
222 const double PI = 3.1415926535;
223
224 // chars can contain 1 character that are surrounded with ' and is one byte in size
225 char myGrade = 'A';
226
227 // bools have the value of (true/1) or (false/0)
228 bool isHappy = true;
229
230 // ints are whole numbers
231 int myAge = 39;
232
233 // floats are floating point numbers accurate to about 6 decimals
234 float favNum = 3.141592;
235
236 // doubles are floating point numbers accurate to about 15 digits
237 double otherFavNum = 1.6180339887;
238
239 // You can output a variable value like this
240 cout << "Favorite Number " << favNum << endl;
241
242 // Other types include
243 // short int : At least 16 bits
244 // long int : At least 32 bits
245 // long long int : At least 64 bits
246 // unsigned int : Same size as signed version
247 // long double : Not less then double
248
249 // You can get the number of bytes for a data type with sizeof
250
251 cout << "Size of int " << sizeof(myAge) << endl;
252 cout << "Size of char " << sizeof(myGrade) << endl;
253 cout << "Size of bool " << sizeof(isHappy) << endl;
254 cout << "Size of float " << sizeof(favNum) << endl;
255 cout << "Size of double " << sizeof(otherFavNum) << endl;
256
257 int largestInt = 2147483647;
258
259 cout << "Largest int " << largestInt << endl;
260
261 // ---------- ARITHMETIC ----------
262 // The arithmetic operators are +, -, *, /, %, ++, --
263
264 cout << "5 + 2 = " << 5+2 << endl;
265 cout << "5 - 2 = " << 5-2 << endl;
266 cout << "5 * 2 = " << 5*2 << endl;
267 cout << "5 / 2 = " << 5/2 << endl;
268 cout << "5 % 2 = " << 5%2 << endl;
269
270 int five = 5;
271 cout << "5++ = " << five++ << endl;
272 cout << "++5 = " << ++five << endl;
273 cout << "5-- = " << five-- << endl;
274 cout << "--5 = " << --five << endl;
275
276 // Shorthand assignment operators
277 // a += b == a = a + b
278 // There is also -=, *=, /=, %=
279
280 // Order of Operation states * and / is performed before + and -
281
282 cout << "1 + 2 - 3 * 2 = " << 1 + 2 - 3 * 2 << endl;
283 cout << "(1 + 2 - 3) * 2 = " << (1 + 2 - 3) * 2 << endl;
284
285 // ---------- CASTING ----------
286 // You convert from one data type to another by casting
287 // char, int, float, double
288
289 cout << "4 / 5 = " << 4 / 5 << endl;
290 cout << "4 / 5 = " << (float) 4 / 5 << endl;
291
292 // ---------- IF STATEMENT ----------
293 // Executes different code depending upon a condition
294
295 // Comparison operators include ==, !=, >, <, >=, <=
296 // Will return true (1) if the comparison is true, or false (0)
297
298 // Logical operators include &&, ||, !
299 // Used to test 2 or more conditionals
300
301 int age = 70;
302 int ageAtLastExam = 16;
303 bool isNotIntoxicated = true;
304
305 if((age >= 1) && (age < 16)){
306 cout << "You can't drive" << endl;
307 } else if(!isNotIntoxicated){
308 cout << "You can't drive" << endl;
309 } else if(age >= 80 && ((age > 100) || ((age - ageAtLastExam) > 5))){
310 cout << "You can't drive" << endl;
311 } else {
312 cout << "You can drive" << endl;
313 }
314
315 // ---------- SWITCH STATEMENT ----------
316 // switch is used when you have a limited number of possible options
317
318 int greetingOption = 2;
319
320 switch(greetingOption){
321
322 case 1 :
323 cout << "bonjour" << endl;
324 break;
325
326 case 2 :
327 cout << "Hola" << endl;
328 break;
329
330 case 3 :
331 cout << "Hallo" << endl;
332 break;
333
334 default :
335 cout << "Hello" << endl;
336 }
337
338 // ---------- TERNARY OPERATOR ----------
339 // Performs an assignment based on a condition
340 // variable = (condition) ? if true : if false
341
342 int largestNum = (5 > 2) ? 5 : 2;
343
344 cout << "The biggest number is " << largestNum << endl;
345
346 // ---------- ARRAYS ----------
347 // Arrays store multiple values of the same type
348
349 // You must provide a data type and the size of the array
350 int myFavNums[5];
351
352 // You can declare and add values in one step
353 int badNums[5] = {4, 13, 14, 24, 34};
354
355 // The first item in the array has the label (index) of 0
356 cout << "Bad Number 1: " << badNums[0] << endl;
357
358 // You can create multidimensional arrays
359 char myName[5][5] = {{'D','e','r','e','k'},{'B','a','n','a','s'}};
360
361 cout << "2nd Letter in 2nd Array: " << myName[1][1] << endl;
362
363 // You can change a value in an array using its index
364 myName[0][2] = 'e';
365
366 cout << "New Value " << myName[0][2] << endl;
367
368 // ---------- FOR LOOP ----------
369 // Continues to execute code as long as a condition is true
370
371 for(int i = 1; i <= 10; i++){
372
373 cout << i << endl;
374
375 }
376
377 // You can also cycle through an array by nesting for loops
378 for(int j = 0; j < 5; j++){
379
380 for(int k = 0; k < 5; k++){
381 cout << myName[j][k];
382 }
383
384 cout << endl;
385
386 }
387
388 // ---------- WHILE LOOP ----------
389 // Use a while loop when you don't know ahead of time when a loop will end
390
391 // Generate a random number between 1 and 100
392 int randNum = (rand() % 100) + 1;
393
394 while(randNum != 100){
395
396 cout << randNum << ", ";
397
398 // Used to get you out of the loop
399 randNum = (rand() % 100) + 1;
400
401 }
402
403 cout << endl;
404
405 // You can do the same as the for loop like this
406 // Create an index to iterate out side the while loop
407 int index = 1;
408
409 while(index <= 10){
410
411 cout << index << endl;
412
413 // Increment inside the loop
414 index++;
415
416 }
417
418 // ---------- DO WHILE LOOP ----------
419 // Used when you want to execute what is in the loop at least once
420
421 // Used to store a series of characters
422 string numberGuessed;
423 int intNumberGuessed = 0;
424
425 do {
426 cout << "Guess between 1 and 10: ";
427
428 // Allows for user input
429 // Pass the source and destination of the input
430 getline (cin,numberGuessed);
431
432 // stoi converts the string into an integer
433 intNumberGuessed = stoi(numberGuessed);
434 cout << intNumberGuessed << endl;
435
436 // We'll continue looping until the number entered is 4
437 } while (intNumberGuessed != 4);
438
439 cout << "You Win" << endl;
440
441 // ---------- STRINGS ----------
442 // The string library class provides a string object
443 // You must always surround strings with "
444 // Unlike the char arrays in c, the string object automatically resizes
445
446 // The C way of making a string
447 char happyArray[6] = {'H', 'a', 'p', 'p', 'y', '\0'};
448
449 // The C++ way
450 string birthdayString = " Birthday";
451
452 // You can combine / concatenate strings with +
453 cout << happyArray + birthdayString << endl;
454
455 string yourName;
456 cout << "What is your name? ";
457 getline (cin,yourName);
458
459 cout << "Hello " << yourName << endl;
460
461 double eulersConstant = .57721;
462 string eulerGuess;
463 double eulerGuessDouble;
464 cout << "What is Euler's Constant? ";
465 getline (cin,eulerGuess);
466
467 // Converts a string into a double
468 // stof() for floats
469 eulerGuessDouble = stod(eulerGuess);
470
471 if(eulerGuessDouble == eulersConstant){
472
473 cout << "You are right" << endl;
474
475 } else {
476
477 cout << "You are wrong" << endl;
478
479 }
480
481 // Size returns the number of characters
482 cout << "Size of string " << eulerGuess.size() << endl;
483
484 // empty tells you if string is empty or not
485 cout << "Is string empty " << eulerGuess.empty() << endl;
486
487 // append adds strings together
488 cout << eulerGuess.append(" was your guess") << endl;
489
490 string dogString = "dog";
491 string catString = "cat";
492
493 // Compare returns a 0 for a match, 1 if less than, -1 if greater then
494 cout << dogString.compare(catString) << endl;
495 cout << dogString.compare(dogString) << endl;
496 cout << catString.compare(dogString) << endl;
497
498 // assign copies a value to another string
499 string wholeName = yourName.assign(yourName);
500 cout << wholeName << endl;
501
502 // You can get a substring as well by defining the starting index and the
503 // number of characters to copy
504 string firstName = wholeName.assign(wholeName, 0, 5);
505 cout << firstName << endl;
506
507 // find returns the index for the string your searching for starting
508 // from the index defined
509 int lastNameIndex = yourName.find("Banas", 0);
510 cout << "Index for last name " << lastNameIndex << endl;
511
512 // insert places a string in the index defined
513 yourName.insert(5, " Justin");
514 cout << yourName << endl;
515
516 // erase will delete 6 characters starting at index 7
517 yourName.erase(6,7);
518 cout << yourName << endl;
519
520 // replace 5 characters starting at index 6 with the string Maximus
521 yourName.replace(6,5,"Maximus");
522 cout << yourName << endl;
523
524 // ---------- VECTORS ----------
525 // Vectors are like arrays, but their size can change
526
527 vector <int> lotteryNumVect(10);
528
529 int lotteryNumArray[5] = {4, 13, 14, 24, 34};
530
531 // Add the array to the vector starting at the beginning of the vector
532 lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, lotteryNumArray+3);
533
534 // Insert a value into the 5th index
535 lotteryNumVect.insert(lotteryNumVect.begin()+5, 44);
536
537 // at gets the value in the specified index
538 cout << "Value in 5 " << lotteryNumVect.at(5) << endl;
539
540 // push_back adds a value at the end of a vector
541 lotteryNumVect.push_back(64);
542
543 // back gets the value in the final index
544 cout << "Final Value " << lotteryNumVect.back() << endl;
545
546 // pop_back removes the final element
547 lotteryNumVect.pop_back();
548
549 // front returns the first element
550 cout << "First Element " << lotteryNumVect.front() << endl;
551
552 // back returns the last element
553 cout << "Last Element " << lotteryNumVect.back() << endl;
554
555 // empty tells you if the vector is empty
556 cout << "Vector Empty " << lotteryNumVect.empty() << endl;
557
558 // size returns the total number of elements
559 cout << "Number of Vector Elements " << lotteryNumVect.size() << endl;
560
561 // ---------- FUNCTIONS ----------
562 // Functions allow you to reuse and better organize your code
563
564 cout << addNumbers(1) << endl;
565
566 // You can't access values created in functions (Out of Scope)
567 // cout << combinedValue << endl;
568
569 cout << addNumbers(1, 5, 6) << endl;
570
571 cout << "The factorial of 3 is " << getFactorial(3) << endl;
572
573 // ---------- FILE I/O ----------
574 // We can read and write to files using text or machine readable binary
575
576 string steveQuote = "A day without sunshine is like, you know, night";
577
578 // Create an output filestream and if the file doesn't exist create it
579 ofstream writer("stevequote.txt");
580
581 // Verify that the file stream object was created
582 if(! writer){
583
584 cout << "Error opening file" << endl;
585
586 // Signal that an error occurred
587 return -1;
588
589 } else {
590
591 // Write the text to the file
592 writer << steveQuote << endl;
593
594 // Close the file
595 writer.close();
596
597 }
598
599 // Open a stream to append to whats there with ios::app
600 // ios::binary : Treat the file as binary
601 // ios::in : Open a file to read input
602 // ios::trunc : Default
603 // ios::out : Open a file to write output
604 ofstream writer2("stevequote.txt", ios::app);
605
606 if(! writer2){
607
608 cout << "Error opening file" << endl;
609
610 // Signal that an error occurred
611 return -1;
612
613 } else {
614
615 writer2 << "\n- Steve Martin" << endl;
616 writer2.close();
617
618 }
619
620 char letter;
621
622 // Read characters from a file using an input file stream
623 ifstream reader("stevequote.txt");
624
625 if(! reader){
626
627 cout << "Error opening file" << endl;
628 return -1;
629
630 } else {
631
632 // Read each character from the stream until end of file
633 for(int i = 0; ! reader.eof(); i++){
634
635 // Get the next letter and output it
636 reader.get(letter);
637 cout << letter;
638
639 }
640
641 cout << endl;
642 reader.close();
643
644 }
645
646 // ---------- EXCEPTION HANDLING ----------
647 // You can be prepared for potential problems with exception handling
648
649 int number = 0;
650
651 try{
652
653 if(number != 0){
654 cout << 2/number << endl;
655 } else throw(number);
656
657 }
658 catch(int number){
659
660 cout << number << " is not valid input" << endl;
661
662 }
663
664 // ---------- POINTERS ----------
665 // When data is stored it is stored in an appropriately sized box based
666 // on its data type
667
668 int myAge = 39;
669 char myGrade = 'A';
670
671 cout << "Size of int " << sizeof(myAge) << endl;
672 cout << "Size of char " << sizeof(myGrade) << endl;
673
674 // You can reference the box (memory address) where data is stored with
675 // the & reference operator
676
677 cout << "myAge is located at " << &myAge << endl;
678
679 // A pointer can store a memory address
680 // The data type must be the same as the data referenced and it is followed
681 // by a *
682
683 int* agePtr = &myAge;
684
685 // You can access the memory address and the data
686 cout << "Address of pointer " << agePtr << endl;
687
688 // * is the dereference or indirection operator
689 cout << "Data at memory address " << *agePtr << endl;
690
691 int badNums[5] = {4, 13, 14, 24, 34};
692 int* numArrayPtr = badNums;
693
694 // You can increment through an array using a pointer with ++ or --
695 cout << "Address " << numArrayPtr << " Value " << *numArrayPtr << endl;
696 numArrayPtr++;
697 cout << "Address " << numArrayPtr << " Value " << *numArrayPtr << endl;
698
699 // An array name is just a pointer to the array
700 cout << "Address " << badNums << " Value " << *badNums << endl;
701
702 // When you pass a variable to a function you are passing the value
703 // When you pass a pointer to a function you are passing a reference
704 // that can be changed
705
706 makeMeYoung(&myAge);
707
708 cout << "I'm " << myAge << " years old now" << endl;
709
710 // & denotes that ageRef will be a reference to the assigned variable
711 int& ageRef = myAge;
712
713 cout << "ageRef : " << ageRef << endl;
714
715 // It can manipulate the other variables data
716 ageRef++;
717
718 cout << "myAge : " << myAge << endl;
719
720 // You can pass the reference to a function
721 actYourAge(ageRef);
722
723 cout << "myAge : " << myAge << endl;
724
725 // When deciding on whether to use pointers or references
726 // Use Pointers if you don't want to initialize at declaration, or if
727 // you need to assign another variable
728 // otherwise use a reference
729
730 // ---------- CLASSES & OBJECTS ----------
731 // Classes are the blueprints for modeling real world objects
732 // Real world objects have attributes, classes have members / variables
733 // Real world objects have abilities, classes have methods / functions
734 // Classes believe in hiding data (encapsulation) from outside code
735
736 // Declare a Animal type object
737 Animal fred;
738
739 // Set the values for the Animal
740 fred.setHeight(33);
741 fred.setWeight(10);
742 fred.setName("Fred");
743
744 // Get the values for the Animal
745 cout << fred.getName() << " is " << fred.getHeight() << " cms tall and "
746 << fred.getWeight() << " kgs in weight" << endl;
747
748 fred.setAll(34, 12, "Fred");
749
750 cout << fred.getName() << " is " << fred.getHeight() << " cms tall and "
751 << fred.getWeight() << " kgs in weight" << endl;
752
753 // Creating an object using the constructor
754 Animal tom(36, 15, "Tom");
755
756 cout << tom.getName() << " is " << tom.getHeight() << " cms tall and "
757 << tom.getWeight() << " kgs in weight" << endl;
758
759 // Demonstrate the inheriting class Dog
760 Dog spot(38, 16, "Spot", "Woof");
761
762 // static methods are called by using the class name and the scope operator
763 cout << "Number of Animals " << Animal::getNumOfAnimals() << endl;
764
765 spot.getSound();
766
767 // Test the toString method that will be overwritten
768 tom.toString();
769 spot.toString();
770
771 // We can call the superclass version of a method with the class name
772 // and the scope operator
773 spot.Animal::toString();
774
775 // When a function finishes it must return an integer value
776 // Zero means that the function ended with success
777 return 0;
778 }

You might also like