Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

817 lines
16 KiB

  1. This post aims to cover all the major topics that C programmers need to know before
  2. they start writing C++ programs. I kept this post as short and concise as possible to
  3. enable people to use this as a quick reference to quickly jump into C++. This post assumes
  4. that you have prior knowledge of both C and object oriented-programming concepts. Each topic
  5. is quickly covered in a code snippet and some additional explanation is provided if necessary.
  6. # Input/Output
  7. Input and output in C++ is easy, you use "cout" and "cin". When printing with
  8. "cout", you separate what your printing with "<<"; "endl" prints a new line.
  9. ```c++
  10. using namespace std; //namespaces talked about below
  11. #include <iostream> //Include statement for terminal IO.
  12. int main()
  13. {
  14. cout << "Hello World" << endl; // HELLO WORLD!
  15. int a;
  16. cin >> a; //inputs an int into a -- notice how arrows face the direction of IO
  17. cout << "You entered: " << a << endl; //prints what you entered
  18. return 0; // return sucess code
  19. }
  20. ```
  21. Save your C++ programs with the extension ".cpp", you then
  22. can compile and run it with g++. Compiling a C++ program with g++ is nearly the same
  23. as compiling a C program with GCC.
  24. ex:
  25. ```bash
  26. g++ helloWorld.cpp -o hello
  27. ./hello
  28. ```
  29. # Namespaces
  30. Name spaces are used to enable you to have multiple functions/methods called the
  31. same thing and not conflict with one another. You use "namespacename::function/variable"
  32. to access something inside of a specific namespace. To prevent you from always having to type
  33. "namespacename::", you can use a namespace which makes that namespace default.
  34. ```c++
  35. using namespace std; //tells compiler we want to use std namespace
  36. #include <iostream>
  37. namespace foo //declares a namespece named foo
  38. {
  39. int a, b;
  40. void fun()
  41. {
  42. cout << "Inside foo namespace" << endl;
  43. }
  44. }
  45. namespace bar
  46. {
  47. void fun() //declares a function with the same name as another function
  48. {
  49. cout << "Inside bar namespace" << endl;
  50. }
  51. }
  52. using namespace foo; //start useing foo instead of std as selected namespace
  53. int main()
  54. {
  55. fun();
  56. bar::fun();
  57. int a = 5;
  58. foo::a = 12;
  59. std::cout << "a: " << a << endl; //had to use std::cout since the default namespace is foo
  60. std::cout << "foo::a: " << foo::a << endl;
  61. return 0;
  62. }
  63. ```
  64. # Global Variable
  65. Global variables are similar to C, however, you can now reference a global members with the "::"
  66. accessor.
  67. ```c++
  68. using namespace std;
  69. #include <iostream>
  70. double bar = 64;
  71. int main ()
  72. {
  73. double bar = 12;
  74. cout << "Local bar: " << bar << endl; //prints 12
  75. cout << "Global bar: " << ::bar << endl; //prints 64
  76. return 0;
  77. }
  78. ```
  79. # Multiple Names for a Variable/Aliasing
  80. This is NOT simply a pointer. In the following example pi, and x now are treated as
  81. the same exact variable. You cannot later change the pointer destination for x.
  82. ```c++
  83. double pi = 3.145;
  84. double &x = pi; //pi is x
  85. x = 2.1;
  86. cout << "pi: " << pi << " x: " << x << endl; // prints pi: 2.1 x: 2.1
  87. ```
  88. # Passing Variables by Reference
  89. In C, everything was passed by value; C++ allows us to pass variables by reference. This is very powerful, in
  90. languages like Java, only Objects are passed by reference. C++ lets you decide exactly
  91. what gets passed by reference or by value -- even primitives.
  92. ```c++
  93. using namespace std;
  94. #include <iostream>
  95. void change (int &r, int s) //& infront of variable means that it will get passed by reference
  96. {
  97. r = 100;
  98. s = 200;
  99. }
  100. int main()
  101. {
  102. int x = 1;
  103. int y = 2;
  104. cout << x << ", " << y << endl;
  105. change(x, y);
  106. cout << x << ", " << y << endl;
  107. return 0;
  108. }
  109. ```
  110. Same code in C. This method still works in C++.
  111. ```c
  112. void change(double *r, double s)
  113. {
  114. *r = 100;
  115. s = 200;
  116. }
  117. int main()
  118. {
  119. int x = 1;
  120. int y = 2;
  121. printf("%d, %d", x, y);
  122. change(&x, y);
  123. printf("%d, %d", x, y);
  124. return 0;
  125. }
  126. ```
  127. # Functions Returning Variables References
  128. A function can return a value reference which can be treated as a variable. In the following example, a function
  129. returns the reference to the variable which is the smallest.
  130. ```c++
  131. using namespace std;
  132. #include <iostream>
  133. int &smallest (int &x, int &y) //smallest returns a reference to a variable
  134. {
  135. if (x < y)
  136. return x;
  137. else
  138. return y;
  139. }
  140. int main ()
  141. {
  142. int k = 33;
  143. int m = 2;
  144. cout << "k: " << k << " m: " << m << endl; // prints k: 33 m: 2
  145. smallest (k, m) = 10; // MAGIC!
  146. cout << "k: " << k << " m: " << m << endl; // prints k: 33 m: 10
  147. return 0;
  148. }
  149. ```
  150. # Inline
  151. Inline can be used to replace a function which contains very simple logic -- no
  152. for loops, etc. Like a macro, this will be inserted everywhere the code is used; a
  153. drawback to inline methods is that the compiled source will be larger. But, they
  154. typically run faster.
  155. ```c++
  156. using namespace std;
  157. #include <iostream>
  158. inline int square(int x) //macro like method
  159. {
  160. return x * x;
  161. }
  162. int main()
  163. {
  164. int k = 4;
  165. cout << square(k) << endl; //prints 16
  166. return 0;
  167. }
  168. ```
  169. # Exceptions
  170. Exceptions might help you stop segmentation faulting. The important thing to notice
  171. is that you can throw about any type in a try block.
  172. ```c++
  173. int x;
  174. cout << "Type a number: ";
  175. cin >> x;
  176. cout << endl;
  177. try
  178. {
  179. if(a > 150)
  180. throw 150;
  181. if(a < 15)
  182. throw 15;
  183. throw a % 2;
  184. }
  185. catch(int result)
  186. {
  187. cout << result << " was thrown." << endl;
  188. }
  189. ```
  190. # Default Parameters for Functions
  191. This is exactly like default parameters in Python. If a function is called without
  192. the parameter, it is assumed to be that value.
  193. ```c++
  194. double multiply(double x, double y = 5) // y has the default value of 5
  195. {
  196. return x * y;
  197. }
  198. int main()
  199. {
  200. cout << multiply(4) << endl; // 20
  201. cout << multiply(4, 4) endl; // 16
  202. return 0;
  203. }
  204. ```
  205. # Function Overloading
  206. Like Java and Python, you can overload methods in C++. Not only can you overload the
  207. methods, but, the return type of the methods which are overloaded don't have to match.
  208. ```c++
  209. double add(double x)
  210. {
  211. return x;
  212. }
  213. double add(double x, double y)
  214. {
  215. return x + y;
  216. }
  217. int add(int x, int y)
  218. {
  219. return x + y;
  220. }
  221. int main()
  222. {
  223. cout << add(4) << endl; // 4
  224. cout << add(4.0, 4.0) << endl; // 8
  225. return 0;
  226. }
  227. ```
  228. # Operator Overloading
  229. You can redefine basic operators like (+,/,-,<<,>>, +=) for certain data types by using
  230. operator overloading.
  231. ```c++
  232. using namespace std;
  233. #include <iostream>
  234. struct tuple //since tuple is defined elsewhere, we need to use :: to access it
  235. {
  236. int x;
  237. int y;
  238. };
  239. ::tuple operator + (int a, ::tuple b)
  240. {
  241. ::tuple r; //creates the tuple from our file -- tuple is defined elsewhere
  242. r.x = a + b.x;
  243. r.y = a + b.y;
  244. return r;
  245. }
  246. ::tuple operator * (int a, ::tuple b)
  247. {
  248. ::tuple r; //creates the tuple from our file -- tuple is defined elsewhere
  249. r.x = a * b.x;
  250. r.y = a * b.y;
  251. return r;
  252. }
  253. int main ()
  254. {
  255. ::tuple k, m; // No need to type "struct vector"
  256. k.x = 2; // To be able to write
  257. k.y = -1; // k = vector (2, -1)
  258. // see chapter 19.
  259. m = 3 + k; // Magic!
  260. cout << "(" << m.x << ", " << m.y << ")" << endl;
  261. return 0;
  262. }
  263. ```
  264. # Functions with Generic Parameter Types
  265. In C++ you can use a template class to create a method which has generic
  266. return and parameter types.
  267. ```c++
  268. template <class ttype> //function with 1 generic type
  269. ttype max (ttype a, ttype b)
  270. {
  271. ttype r;
  272. r = a;
  273. if (b < a)
  274. r = b;
  275. return r;
  276. }
  277. template <class type1, class type2> //function with 2 generic types
  278. type1 maximum (type1 a, type2 b)
  279. {
  280. type1 r, b_converted;
  281. r = a;
  282. b_converted = (type1) b;
  283. if (b_converted > a)
  284. r = b_converted;
  285. return r;
  286. }
  287. ```
  288. # Replacement for malloc and free
  289. Malloc and free still exists in C++, however, people typically
  290. use "new" and "delete" instead because it is cleaner.
  291. ```c++
  292. int *i = new int; //i = malloc(sizeof(int)); //c code
  293. *i = 55;
  294. delete i; //free(i); // c code
  295. i = new int[15];
  296. i[0] = 99;
  297. delete i;
  298. ```
  299. # Struct Functions
  300. You can now add functions to structs.
  301. ```c++
  302. struct pair
  303. {
  304. int i;
  305. int x;
  306. int sum()
  307. {
  308. return i + x;
  309. }
  310. };
  311. ```
  312. # Classes
  313. The syntax of a class is similar to a struct.
  314. ```c++
  315. class Pair
  316. {
  317. public: // encapsulation covered in 2 sections
  318. int i;
  319. int x;
  320. int sum()
  321. {
  322. return i + x;
  323. }
  324. };
  325. ```
  326. ## Class Constructor and De-constructor
  327. Class constructors are similar to constructors in Java. Class destructor
  328. are simply the name of the class with a "~" sign in front of it. It is important to
  329. free any allocated memory in the class deconstruct since C++ does not have a garbage collector.
  330. ```c++
  331. class Pair
  332. {
  333. public:
  334. int i;
  335. int x;
  336. Pair(int i1, int i2) //constructor
  337. {
  338. i = i1;
  339. x = i2;
  340. }
  341. ~Pair() //class deconstructor
  342. {
  343. //delete any memory you have!
  344. }
  345. int sum()
  346. {
  347. return i + x;
  348. }
  349. };
  350. // in main or somewhere
  351. Pair t (12, 14); //creates a tuple on the stack
  352. Pair* tt = new Pair(12, 15); //allocates memory for the tuple on the heap
  353. cout << t.sum() << endl; //prints 26
  354. cout << tt->sum() << endl; //prints 27
  355. ```
  356. ## Encapsulation
  357. Like Java, you can declare who can view access certain members of a class.
  358. - protected: Only members of the class and children can view the variables/methods.
  359. - public: Everyone has access to the variables/methods.
  360. - private: Only this class can access the variables/methods.
  361. ```c++
  362. class Person
  363. {
  364. protected:
  365. int age;
  366. string name;
  367. public:
  368. Person(int age, string name)
  369. {
  370. }
  371. ~Person()
  372. {
  373. }
  374. private:
  375. void increaseAge()
  376. {
  377. age++;
  378. }
  379. };
  380. ```
  381. ## This keyword
  382. When you use the "this" key word, you are getting the pointer to the class that you are
  383. in.
  384. ```c++
  385. class Person
  386. {
  387. protected:
  388. int age;
  389. string name;
  390. public:
  391. Person(int age, string name)
  392. {
  393. this->age = age;
  394. this->name = name;
  395. }
  396. ~Person()
  397. {
  398. }
  399. private:
  400. void increaseAge()
  401. {
  402. age++;
  403. }
  404. };
  405. ```
  406. ## Class Inheritance
  407. Classes can inherit variables and methods from other classes. The most important thing to
  408. remember is that if you ever want to override a method in a child class, you must
  409. declare the method as "virtual".
  410. ```c++
  411. class Pair
  412. {
  413. protected:
  414. int x;
  415. int y;
  416. public:
  417. Pair(int i1, int i2)
  418. {
  419. x = i1;
  420. y = i2;
  421. }
  422. virtual int sum()
  423. {
  424. return x + x;
  425. }
  426. };
  427. class Triple: public Pair
  428. {
  429. protected:
  430. int z;
  431. public:
  432. Triple(int i1, int i2, int i3): Pair(i1, i2) //calls the parent's constructor
  433. {
  434. z = i3;
  435. }
  436. int sum()
  437. {
  438. return x + y + z;
  439. }
  440. };
  441. ```
  442. ## Abstract Classes
  443. Abstract classes are simply classes which cannot be instantiated. To do this in C++
  444. you simply set a virtual function equal to zero.
  445. ```c++
  446. class Animal
  447. {
  448. public:
  449. virtual void speak()=0;
  450. };
  451. class Cat: public Animal
  452. {
  453. public:
  454. void speak()
  455. {
  456. cout << "Meow" << endl;
  457. }
  458. };
  459. ```
  460. ## Method Prototypes for Classes
  461. If you wish to use a method prototype in a class, you must use namespace
  462. syntax to define the method elsewhere. This is particularly useful for breaking classes
  463. into multiple files. It is common to declare the class in a header file and then
  464. implement the functions in a cpp file.
  465. ```c++
  466. class Animal
  467. {
  468. public:
  469. virtual void speak()=0;
  470. };
  471. class Cat: public Animal
  472. {
  473. public:
  474. void speak()
  475. {
  476. cout << "Meow" << endl;
  477. }
  478. int fly(); //method prototype
  479. };
  480. int Cat::fly()
  481. {
  482. return 42;
  483. }
  484. ```
  485. # Strings
  486. Since C++ has classes, you can work with strings in a pleasant way.
  487. ```c++
  488. using namespace std;
  489. #include <iostream>
  490. int main()
  491. {
  492. string str1 = "Hello"; // string "Hello"
  493. string str2("World"); // string "World"
  494. string str1Copy(str1); // string "Hello"
  495. //initializes string by a character and number of occurrences
  496. string str4(5, '$'); // string "$$$$$$"
  497. //string concatenation
  498. string greeting = str1 + " " + str2;
  499. cout << greeting << endl;
  500. //length of a string
  501. int len = str1.size();
  502. cout << "str1.size(): " << len << endl;
  503. //clear all characters from a string
  504. greeting.clear();
  505. cout <<"Greeting: "<< greeting << endl;
  506. string numbers = "0123456789";
  507. //returns first character in string
  508. char first = numbers.front();
  509. //returns last character in string
  510. char back = numbers.back();
  511. //gets a character at a certain position
  512. char second = numbers.at(1);
  513. char secondAlt = numbers[1]; //array syntax still works on strings
  514. cout << "first: " << first << endl;
  515. cout << "back: " << back << endl;
  516. cout << "second: " << second << endl;
  517. //substr(a, b) function returns a substring of b length
  518. //starting from index a. If there is no second argument, it
  519. //goes to the end.
  520. cout << numbers.substr(2, 7) << endl;
  521. //replace(a, b, str) replaces b character from a index by str
  522. string str6 = "This is a examples";
  523. str6.replace(2, 7, "ese are test");
  524. cout << str6 << endl;
  525. return 0;
  526. }
  527. ```
  528. # File IO
  529. File IO is significantly different from C. I will quickly glance over
  530. a few examples which should give you most of what you need to start writing basic programs.
  531. ## Reading from File
  532. Reading a file example by character.
  533. ```c++
  534. using namespace std;
  535. #include <iostream>
  536. #include <fstream> // header for files
  537. int main()
  538. {
  539. fstream f;
  540. char c;
  541. f.open("p022_names.txt", ios::in);
  542. while(!f.eof())
  543. {
  544. f.get(c);
  545. cout << c;
  546. }
  547. f.close();
  548. }
  549. ```
  550. Reading lines from a file using strings.
  551. ```c++
  552. using namespace std;
  553. #include <iostream>
  554. #include <fstream>
  555. #include <string>
  556. int main ()
  557. {
  558. string line;
  559. ifstream myfile ("example.txt");
  560. if(myfile.is_open()) //checks to see if file open successfully
  561. {
  562. while(getline(myfile,line)) //gets contents of file and puts them in a string
  563. {
  564. cout << line << '\n';
  565. }
  566. myfile.close();
  567. }
  568. else
  569. {
  570. cout << "Unable to open file";
  571. }
  572. return 0;
  573. }
  574. ```
  575. ## Writing to File
  576. Writing to a file example.
  577. ```c++
  578. using namespace std;
  579. #include <iostream>
  580. #include <fstream> // Header for files
  581. int main()
  582. {
  583. fstream f;
  584. char c;
  585. f.open("p022_names.txt", ios::out);
  586. f << "stuff in the file " << endl;
  587. int i = 4;
  588. f << i << " this is also in the text file" << endl;
  589. f.close();
  590. }
  591. ```
  592. # Resources
  593. You now know enough C++ to start programming with it. If you want to take your
  594. skills to the next level, I would recommend start working on a few projects in C++ and get
  595. a comprehensive C++ book.
  596. - [Online C++ Guide](https://www.programiz.com/cpp-programming)
  597. - Kochan: Programming in C _p4 (4th Edition) (Developer's Library) 4th Edition -- Really good book if you don't know C yet.
  598. - [Tutorials Point C++](https://www.tutorialspoint.com/cplusplus/index.htm)