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.

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