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.

634 lines
9.5 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)
  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. ```c++
  202. double add(double x)
  203. {
  204. return x + x;
  205. }
  206. double add(double x, double y)
  207. {
  208. return x + y;
  209. }
  210. int add(int x, int y)
  211. {
  212. return x + y;
  213. }
  214. int main()
  215. {
  216. cout << multiply(4) << endl; // 20
  217. cout << multiply(4, 4) endl; // 15
  218. return 0;
  219. }
  220. ```
  221. ## Operator Overloading
  222. ```c++
  223. using namespace std;
  224. #include <iostream>
  225. struct tuple
  226. {
  227. int x;
  228. int y;
  229. };
  230. tuple operator + (int a, vector b)
  231. {
  232. vector r;
  233. r.x = a + b.x;
  234. r.y = a + b.y;
  235. return r;
  236. }
  237. int main ()
  238. {
  239. tuple k, m; // No need to type "struct tuple"
  240. // also no need to typedef
  241. k.x = 3;
  242. k.y = 6;
  243. m = 2 + k; // Voodoo witchcraft
  244. cout << "(" << m.x << ", " << m.y << ")" << endl;
  245. return 0;
  246. }
  247. ```
  248. ## Functions with Generic Parameter Types
  249. ```c++
  250. template <class ttype>
  251. ttype max (ttype a, ttype b)
  252. {
  253. ttype r;
  254. r = a;
  255. if (b < a) r = b;
  256. return r;
  257. }
  258. template <class type1, class type2>
  259. type1 maximum (type1 a, type2 b)
  260. {
  261. type1 r, b_converted;
  262. r = a;
  263. b_converted = (type1) b;
  264. if (b_converted > a)
  265. r = b_converted;
  266. return r;
  267. }
  268. ```
  269. ## Replacement for malloc and free
  270. ```c++
  271. int i*;
  272. i = new int;
  273. *i = 55;
  274. delete i;
  275. i = new int[15];
  276. i[0] = 99;
  277. delete i;
  278. ```
  279. ## Struct Functions
  280. ```c++
  281. struct tuple
  282. {
  283. int i;
  284. int x;
  285. int sum()
  286. {
  287. return i + x;
  288. }
  289. };
  290. ```
  291. # Classes
  292. ```c++
  293. class Tuple
  294. {
  295. public:
  296. int i;
  297. int x;
  298. int sum()
  299. {
  300. return i + x;
  301. }
  302. };
  303. ```
  304. ## Class Constructor and De-constructor
  305. ```c++
  306. class Tuple
  307. {
  308. public:
  309. int i;
  310. int x;
  311. Tuple(int i1, int i2)
  312. {
  313. i = i1;
  314. x = i2;
  315. }
  316. ~Tuple()
  317. {
  318. //delete any memory you have!
  319. }
  320. int sum()
  321. {
  322. return i + x;
  323. }
  324. };
  325. // in main
  326. Tuple t (12, 14);
  327. Tuple tt = new Tuple(12, 15);
  328. ```
  329. ## Scope
  330. ```c++
  331. class Person
  332. {
  333. protected:
  334. int age;
  335. string name;
  336. public:
  337. Person(int age, string name)
  338. {
  339. }
  340. ~Person()
  341. {
  342. }
  343. private:
  344. void increaseAge()
  345. {
  346. age++;
  347. }
  348. }
  349. ```
  350. ## This keyword
  351. ```c++
  352. class Person
  353. {
  354. protected:
  355. int age;
  356. string name;
  357. public:
  358. Person(int age, string name)
  359. {
  360. this->age = age;
  361. strcpy(this->name, name);
  362. }
  363. ~Person()
  364. {
  365. }
  366. private:
  367. void increaseAge()
  368. {
  369. age++;
  370. }
  371. }
  372. ```
  373. ## Class Inheritance
  374. ```c++
  375. class Tuple
  376. {
  377. protected:
  378. int x;
  379. int y;
  380. public:
  381. Tuple(int i1, int i2)
  382. {
  383. x = i1;
  384. y = i2;
  385. }
  386. virtual int sum()
  387. {
  388. return i + x;
  389. }
  390. };
  391. class Triple: public Tuple
  392. {
  393. protected:
  394. int x;
  395. int y;
  396. int z;
  397. public:
  398. Triple(int i1, int i2, i3): Tuple(i1, i2)
  399. {
  400. z = i3;
  401. }
  402. int sum()
  403. {
  404. return x + y + z;
  405. }
  406. };
  407. ```
  408. ## "Abstract" Classes
  409. ```c++
  410. class Animal
  411. {
  412. public:
  413. virtual void speak()=0;
  414. }
  415. class Cat: public Animal
  416. {
  417. public:
  418. void speak()
  419. {
  420. cout << "Meow" << endl;
  421. }
  422. };
  423. ```
  424. ## Method Prototypes for Classes
  425. ```c++
  426. class Cat: public Animal
  427. {
  428. public:
  429. void speak()
  430. {
  431. cout << "Meow" << endl;
  432. }
  433. int fly(); //method prototype
  434. };
  435. // Off in a header file or something
  436. int Cat::fly()
  437. {
  438. return 42;
  439. }
  440. ```
  441. # File IO
  442. ## Reading From File
  443. ```c++
  444. #include <fstream>
  445. //in main or somewhere
  446. fstream f;
  447. char c;
  448. f.open("p022_names.txt", ios::in);
  449. while(!f.eof())
  450. {
  451. f.get(c);
  452. cout << c;
  453. }
  454. f.close();
  455. ```
  456. ## Writing to File
  457. ```c++
  458. #include <fstream>
  459. //in main or somewhere
  460. fstream f;
  461. char c;
  462. f.open("p022_names.txt", ios::out);
  463. f << "stuff in the file " << endl;
  464. int i = 4;
  465. f << i << " this is also in the text file" << endl;
  466. f.close();
  467. ```