{"id":12086,"date":"2017-11-27T16:28:27","date_gmt":"2017-11-27T21:28:27","guid":{"rendered":"http:\/\/jianmingli.com\/wp\/?p=12086"},"modified":"2018-04-13T09:58:54","modified_gmt":"2018-04-13T14:58:54","slug":"book-note-beginning-c","status":"publish","type":"post","link":"https:\/\/jianmingli.com\/wp\/?p=12086","title":{"rendered":"Book Note: Beginning C++"},"content":{"rendered":"<div class='toc wptoc'>\n<h2>Contents<\/h2>\n<ol class='toc-odd level-1'>\n\t<li>\n\t\t<a href=\"#Overview\">Overview<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Namespaces\">Namespaces<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Data_Types\">Data Types<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Integer\">Integer<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Constants\">Constants<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Integer_Operators\">Integer Operators<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Explicit_Type_Casting\">Explicit Type Casting<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Floating-Point\">Floating-Point<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#lvalue_and_rvalue\">lvalue and rvalue<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Bitwise_operators\">Bitwise operators<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Enumerated_Data_Types\">Enumerated Data Types<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Synonyms_for_data_types:_typedef\">Synonyms for data types: typedef<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Variable_Scopes\">Variable Scopes<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Comparisons\">Comparisons<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Conditions\">Conditions<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Arrays\">Arrays<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Loops\">Loops<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Pointers_and_References\">Pointers and References<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Pointer\">Pointer<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Address-Of_Operator:_\">Address-Of Operator: &<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Indirection_Operator:_\">Indirection Operator: *<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Dynamic_Memory_Allocation\">Dynamic Memory Allocation<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Smart_Pointers\">Smart Pointers<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#References\">References<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Functions\">Functions<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Lamda_Expressions\">Lamda Expressions<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Preprocessing_Directives\">Preprocessing Directives<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Linkage_for_a_Name\">Linkage for a Name<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Preprocessing_Source_Code\">Preprocessing Source Code<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Using_Header_Files\">Using Header Files<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Classes\">Classes<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Operator_Overloading\">Operator Overloading<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Inheritance\">Inheritance<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Polymorphism\">Polymorphism<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Runtime_Errors_and_Exception\">Runtime Errors and Exception<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#Class_Templates\">Class Templates<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#File_IO\">File IO<\/a>\n\t<\/li>\n\t<li>\n\t\t<a href=\"#References_1\">References<\/a>\n\t<\/li>\n<\/ol>\n<\/ol>\n<\/div>\n<div class='wptoc-end'>&nbsp;<\/div>\n<span id=\"Overview\"><h2>Overview<\/h2><\/span>\n<p>* Latest standard: C++14<br \/>\n* Compile command with Visual Studion command line<\/p>\n<pre lang=\"bash\">\r\ncl \/EHsc test.cpp\r\n<\/pre>\n<p>* Comments (same as Java and C#):<\/p>\n<pre lang=\"cpp\">\r\n\/\/ this is a comment\r\n\/* this is another\r\n   comment\r\n*\/\r\n<\/pre>\n<p>* Preprocessing directives and header files<br \/>\n&#8211; Header files: contains definitions such as variable and function definitions<br \/>\n&#8211; May not contain implementations,<br \/>\n&#8211; So that source files can be compiled without implementation<\/p>\n<pre lang=\"cpp\">\r\n#include <iostream>\r\n<\/pre>\n<p>* Functions<\/p>\n<pre lang=\"cpp\">\r\nint main()\r\n{\r\n  int answer {42};\r\n  std::cout << \"Hello world! The answer is \"\r\n    << answer\r\n\t<< std::endl;\r\n  return 0;\r\n}\r\n<\/pre>\n<p>* Templates<br \/>\n- Class templates: used by compiler to generate classes<br \/>\n- Function templates: used by compiler to generate functions<\/p>\n<p>* Program files<br \/>\n- Source files: .cpp<br \/>\n- Header files: .h or .hpp<br \/>\n- Other files, e.g. resource files<\/p>\n<p>* Standard Library<br \/>\n* Standard template library (STL): is a subset of standard library<\/p>\n<p>* How an executable file is created:<br \/>\n- source fiels > compile into > object files > linked into > executable file<\/p>\n<span id=\"Namespaces\"><h3>Namespaces<\/h3><\/span>\n<p>* Only function prototype are required to be in a namespace<\/p>\n<pre lang=\"cpp\">\r\n\/\/ Define namespace\r\nnamespace my_ns {\r\n\t\/\/ function prototypes\r\n}\r\n\r\n\/\/ import namespace\r\nusing namespace my_ns;\r\nusing namespace std;\r\nusing std::cout;\r\n<\/pre>\n<p>* Unnamed namespace:<br \/>\n- everything that's defined can NOT be accessed outside the unnamed namespace<\/p>\n<pre lang=\"cpp\">\r\nnamespace {\r\n\t\/\/ function prototypes\r\n}\r\n\r\n* Nested namespaces\r\n<pre lang=\"cpp\">\r\nouter::inner::normalize(data);\r\n<\/pre>\n<p>* Namespace alias<\/p>\n<pre lang=\"cpp\">\r\nnamespace alias_name = original_namespace_name;\r\n\r\n\/\/ for example:\r\nnamespace ublas = boost::numeric::ublas;\r\nublas::vector<double> v;\r\n<\/pre>\n<span id=\"Data_Types\"><h2>Data Types<\/h2><\/span>\n<span id=\"Integer\"><h3>Integer<\/h3><\/span>\n<p>* int<\/p>\n<pre lang=\"cpp\">\r\nint apple_count;\r\nint apple_count {15};\r\nint foot_count {2}, toe_count {10}, head_count {1};\r\n<\/pre>\n<p>* Signed Integer Types<br \/>\nsigned char: 1 byte<br \/>\nshort<br \/>\nshort int: 2 bytes<br \/>\nint: 4 bytes<br \/>\nlong<br \/>\nlong int: 4 bytes<br \/>\nlong long<br \/>\nlong long int: 8 bytes<\/p>\n<pre lang=\"cpp\">\r\nsigned char ch {20};\r\nlong temperature {-50L};\r\nlong width {500L};\r\nlong long height {250LL};\r\nunsigned int toe_count {10U};\r\nunsigned long angel_count {1000000UL};\r\n<\/pre>\n<span id=\"Constants\"><h3>Constants<\/h3><\/span>\n<pre lang=\"cpp\">\r\nconst unsigned int toe_count {2U};\r\n<\/pre>\n<span id=\"Integer_Operators\"><h3>Integer Operators<\/h3><\/span>\n<p>+ - * \/ %<br \/>\nop=, e.g. += -= *= \/=<br \/>\n++var var++ --var var--<br \/>\nsizeof: bytes occupied by a type<\/p>\n<span id=\"Explicit_Type_Casting\"><h3>Explicit Type Casting<\/h3><\/span>\n<p>static_cast<type_to_convert_to>(expression)<\/p>\n<pre lang=\"cpp\">\r\ndouble value1 {10.5};\r\ndouble value2 {15.5};\r\nint whole_number {static_cast<int>(value1) + static_cast<int>(value2)};\r\n<\/pre>\n<span id=\"Floating-Point\"><h3>Floating-Point<\/h3><\/span>\n<p>float: pricision 7<br \/>\ndouble: pricision 15<br \/>\nlong double: : pricision 19<\/p>\n<span id=\"lvalue_and_rvalue\"><h3>lvalue and rvalue<\/h3><\/span>\n<span id=\"Bitwise_operators\"><h3>Bitwise operators<\/h3><\/span>\n<pre lang=\"cpp\">\r\n~ & ^ |\r\n<\/pre>\n<span id=\"Enumerated_Data_Types\"><h3>Enumerated Data Types<\/h3><\/span>\n<pre lang=\"cpp\">\r\n#include <iostream>\r\n#include <iomanip>\r\nusing std::setw;\r\n\r\nint main()\r\n{\r\n  enum class Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }\r\n                                    yesterday{ Day::Monday }, today{ Day::Tuesday },                                     tomorrow{ Day::Wednesday };\r\n  Day poets_day{ Day::Friday };\r\n\r\n  enum class Punctuation : char { Comma = ',', Exclamation = '!', Question = '?' };\r\n  Punctuation ch{ Punctuation::Comma };\r\n\r\n  std::cout << \"yesterday's value is \" << static_cast<int>(yesterday)\r\n    << static_cast<char>(ch) << \" but poets_day's is \" << static_cast<int>(poets_day)\r\n    << static_cast<char>(Punctuation::Exclamation) << std::endl;\r\n\r\n  today = Day::Thursday;                    \/\/ Assign a new ...\r\n  ch = Punctuation::Question;               \/\/ ... enumerator values\r\n  tomorrow = poets_day;                     \/\/ Copy enumerator value\r\n\r\n  std::cout << \"Is today's value(\" << static_cast<int>(today)\r\n   << \") the same as poets_day(\" << static_cast<int>(poets_day)\r\n   << \")\" << static_cast<char>(ch) << std::endl;\r\n\r\n\/\/   ch = tomorrow;                         \/\/ Uncomment ...\r\n\/\/   tomorrow = Friday;                     \/\/ ... any of these ...\r\n\/\/   today = 6;                             \/\/ ... for an error.\r\n}\r\n<\/pre>\n<span id=\"Synonyms_for_data_types:_typedef\"><h3>Synonyms for data types: typedef<\/h3><\/span>\n<pre lang=\"cpp\">\r\ntypedef long BigOnes;                  \/\/ Defines BigOnes as a type alias\r\nBigOnes mynum {};                      \/\/ Define & initialize as type long\r\n\r\nusing BigOnes = long;                  \/\/ Defines BigOnes as a type alias\r\nusing PhoneBook = std::map<std::shared_ptr<Contact>, std::string>;\r\n<\/pre>\n<span id=\"Variable_Scopes\"><h3>Variable Scopes<\/h3><\/span>\n<p>* Global variables<br \/>\n* Static variables: defined within a block but continue to exist during program lifetime<\/p>\n<pre lang=\"cpp\">\r\nint& f() {\r\n    static int x = 0;\r\n    return x;\r\n} \r\n<\/pre>\n<p>* External variables: variable defined in another source file<\/p>\n<pre lang=\"cpp\">\r\n\/\/ File1.cpp\r\nint shared_value {100};           \/\/ Global variable\r\n\r\n\/\/ Other program code ...\r\n\r\n\/\/ File2.cpp\r\nextern int shared_value;         \/\/ Declare variable to be external\r\n\r\nint main()\r\n{\r\n  int local_value {shared_value + 10};\r\n  \/\/ Plus other code...\r\n}\r\n<\/pre>\n<span id=\"Comparisons\"><h3>Comparisons<\/h3><\/span>\n<p>* Comparison operators:<\/p>\n<pre lang=\"cpp\">\r\n< <= > >= == !=\r\n<\/pre>\n<p>* Logical operators:<\/p>\n<pre lang=\"cpp\">\r\n&& || !\r\n<\/pre>\n<span id=\"Conditions\"><h3>Conditions<\/h3><\/span>\n<p>* if\/else if\/else<br \/>\n* switch<\/p>\n<span id=\"Arrays\"><h3>Arrays<\/h3><\/span>\n<pre lang=\"cpp\">\r\ndouble temperatures[366];\r\ntemperatures[3] = 70.0;\r\n\r\nunsigned int height[6] {};\r\nunsigned int height[6] {26, 37, 47, 55, 62, 75};\r\n\r\n\/\/ std::array<T, N>\r\nstd::array<double, 100> values;\r\nvalues.fill(3.1415926);\r\ndouble total {};\r\nfor(size_t i {} ; i < values.size() ; ++i)\r\n{\r\n  total += values[i];\r\n  \/\/total += values.at(i);\r\n  \r\n}\r\nfor(auto value : values)\r\n{\r\n  total += value;\r\n}\r\n\r\n<\/pre>\n<span id=\"Loops\"><h2>Loops<\/h2><\/span>\n<p>* for loop<\/p>\n<pre lang=\"cpp\">\r\nint sum {};\r\nfor(size_t i {} ; i < sizeof (values)\/sizeof (values[0]) ; ++i)\r\n{\r\n\tsum += values[i];\r\n}\r\n  \r\nint values [] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};\r\nint total {};\r\nfor(int x : values)\r\n\ttotal += x;  \r\n<\/pre>\n<p>* while loop<\/p>\n<pre lang=\"cpp\">\r\nwhile(){\r\n\t\/\/continue;\r\n\t\/\/break;\r\n}\r\n\r\ndo{\r\n}while()\r\n<\/pre>\n<span id=\"Pointers_and_References\"><h2>Pointers and References<\/h2><\/span>\n<span id=\"Pointer\"><h3>Pointer<\/h3><\/span>\n<p>* A pointer is a variable that can be used to store an address<\/p>\n<pre lang=\"cpp\">\r\n\/\/ Define a pointer\r\nlong* pnumber{nullptr};\r\n<\/pre>\n<span id=\"Address-Of_Operator:_\"><h3>Address-Of Operator: &<\/h3><\/span>\n<p>* Obtains the address of a variable<\/p>\n<pre lang=\"cpp\">\r\n\/\/ Define a number\r\nlong number {12345L};\r\n\/\/ Assign address of number variable to pnumber pointer\r\nlong* pnumber {&number};\r\n<\/pre>\n<span id=\"Indirection_Operator:_\"><h3>Indirection Operator: *<\/h3><\/span>\n<p>* aka dereference operator<br \/>\n* Applying * to a ponter accesses the contents of the memory location to which it points<\/p>\n<pre lang=\"cpp\">\r\n\tlong number {12345L};\r\n\tlong* pnumber {nullptr};\r\n\tpnumber = &number;\r\n\t\r\n\tstd::cout << \"Dereferencing, *pnumber = \" << *pnumber << std::endl;\r\n<\/pre>\n<p>* Constant pointer pointing to constant array:<br \/>\n- Array elements cannot be modified<\/p>\n<pre lang=\"cpp\">\r\nconst char* const pstars[] {\r\n\t \"Fatty Arbuckle\", \"Clara Bow\",\r\n\t \"Lassie\", \"Slim Pickens\",\r\n\t \"Boris Karloff\", \"Mae West\",\r\n\t \"Oliver Hardy\", \"Greta Garbo\"\r\n   };\r\n<\/pre>\n<span id=\"Dynamic_Memory_Allocation\"><h3>Dynamic Memory Allocation<\/h3><\/span>\n<pre lang=\"cpp\">\r\n\/\/ declare a pointer of double type\r\ndouble* pvalue{nullptr};\r\n\/\/ reserver memory for pvalue\r\npvalue = new double;\r\n\/\/ assign value to pointer\r\n*pvalue = 3.14;\r\n\/\/ release memory reserved by pointer\r\ndelete pvalue;\r\npvalue = nullptr;\r\n\r\n\/\/ another way\r\ndouble* pval2 {nullptr};\r\npval2 = new double{3.14};\r\n\/\/ release memory reserved by pointer\r\ndelete pval2;\r\npval2 = nullptr;\r\n\r\n\/\/ third way\r\ndoulbe* pval3 {new double{3.14});\r\n\/\/ release memory reserved by pointer\r\ndelete pval3;\r\npval3 = nullptr;\r\n<\/pre>\n<span id=\"Smart_Pointers\"><h3>Smart Pointers<\/h3><\/span>\n<p>* A unique_ptr<T> object behaves as a pointer to type T and is unique,<br \/>\n- which means there cannot be more than one unique_ptr<T> object containing the same address<\/p>\n<pre lang=\"cpp\">\r\nstd::unique_ptr<double> pdata {new double{999.0}};\r\n\/\/ reset to nullptr\r\npdata.reset(); \r\n<\/pre>\n<p>* A shared_ptr<T> object behaves as a pointer to type T,<br \/>\n- in contrast with unique_ptr<T>, there can be any number of shared_ptr<T> objects containing the same address. <\/p>\n<pre lang=\"cpp\">\r\nstd::shared_ptr<double> pdata {new double{999.0}};\r\n\/\/ or better\r\nauto pdata = std::make_shared<double>(999.0); \r\n<\/pre>\n<p>* A weak_ptr<T> is linked to a shared_ptr<T> and contains the same address.<br \/>\n- Its memory will be released when the last shared_ptr<T> referencing it is destroyed or reassigned to point to a different address, even though associated weak_ptr<T> objects may still exist.<\/p>\n<pre lang=\"cpp\">\r\nauto pData = std::make_shared<X>();     \/\/ Create a pointer to an object of type X\r\nstd::weak_ptr<X> pwData {pData};        \/\/ Create a weak pointer from shared pointer\r\nstd::weak_ptr<X> pwData2 {pwData};      \/\/ Create a weak pointer from another\r\n<\/pre>\n<span id=\"References\"><h3>References<\/h3><\/span>\n<p>* lvalue reference<\/p>\n<pre lang=\"cpp\">\r\ndouble data {3.5};\r\n\/\/ define lvlaue reference for data variable\r\ndouble& rdata {data};\r\n\/\/ use exactly like data varilable (no need to dereference like using pointer)\r\nrdata += 2.5;\r\n\r\n\/\/ use reference to modify an array\r\ndouble temperatures[] {45.5, 50.0. 48.2. 57.0. 63.8};\r\nconst double F_to_C {5.0\/9.0};         \/\/ Convert Fahrenheit to Centigrade\r\nfor(auto& t : temperatures)            \/\/ lvalue reference loop variable\r\n  t = (t - 32.0)*FtoC;\r\n<\/pre>\n<span id=\"Functions\"><h2>Functions<\/h2><\/span>\n<p>* Syntax<\/p>\n<pre lang=\"cpp\">\r\nreturn_type function_name (parameter_list)\r\n{\r\n  \/\/ Code for the function...\r\n}\r\n<\/pre>\n<p>* Funciton prototypes<br \/>\n- Function prototypes are declared either in the beginning of source file or in header files<br \/>\n- Actual implementation can appear later in the source file<br \/>\n- So that they can be used in main()<\/p>\n<pre lang=\"cpp\">\r\n\/\/ function prototype so that you can use this funciton in main()\r\ndouble power(double x, int n);\r\n\r\nint main(){\r\n\t\/\/ use function\r\n}\r\n\r\n\/\/ Actual function implementaiton\r\ndouble power(double x, int n){\r\n\t\/\/ implementation\r\n}\r\n<\/pre>\n<p>* Pass by pointer <\/p>\n<pre lang=\"cpp\">\r\n#include <iostream>\r\n\r\ndouble change_it(double* pointer_to_it);\r\n\r\nint main(){\r\n\tdouble it{5.0};\r\n\tdouble result {change_it(&it)};\r\n\tstd::cout << \"Outside function, result = \" << result << std::endl;\r\n}\r\n\r\ndouble change_it(double* pit){\r\n\t*pit += 10.0;\r\n\tstd::cout << \"Within function, *pit = \" << *pit << std::endl;\r\n\treturn *pit;\r\n}\r\n<\/pre>\n<p>* Pass by reference<\/p>\n<pre lang=\"cpp\">\r\n<\/pre>\n<p>* Arguments to main()<\/p>\n<pre lang=\"cpp\">\r\n#include <iostream>\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n  for (int i {} ; i < argc ; ++i)\r\n    std::cout << i << \": \" << argv[i] << std::endl;\r\n}\r\n<\/pre>\n<p>* Default arguments<\/p>\n<pre lang=\"cpp\">\r\n\/\/ Define default argument value in function prototype\r\nvoid show_error(const string& message =\u00a0\"Program Error\");\r\n\r\nvoid show_error(const string& message)\r\n{\u00a0\u00a0\r\n\tstd::cout << message << std::endl;\r\n}\r\n\r\nshow_error(); \/\/ outputs \"Program Error\"\r\n<\/pre>\n<p>* Return values from a function<br \/>\n- never return address of a local variable from a function<br \/>\n- never return a reference to a local variable from a function<\/p>\n<pre lang=\"cpp\">\r\nstring& larger(string& s1, string& s2)\r\n{\r\n  return s1 > s2 ? s1 : s2;             \/\/ Return a reference to the larger string\r\n}\r\n<\/pre>\n<p>* Inline functions<br \/>\n- place them in header files<br \/>\n- it signals that compiler can rewrite the function for performance gains<\/p>\n<pre lang=\"cpp\">\r\ninline int larger(int m, int n)\r\n{\r\n  return m  > n ? m  : n;\r\n}\r\n<\/pre>\n<p>* static variables inside a function<br \/>\n- so that variable values can be retains throughout runtime<\/p>\n<pre lang=\"cpp\">void nextInteger()\r\n{\r\n  static int count {1}; \/\/ retains thru entire runtime\r\n  std::cout << count++ << std::endl;\r\n}\r\n<\/pre>\n<p>* Function overloading<\/p>\n<p>* Function template<\/p>\n<pre lang=\"cpp\">\r\ntemplate <typename T> T larger(T a, T b);    \/\/ Function template prototype\r\n\r\nint main(){\r\n\tstd::cout << \"Larger of 1.5 and 2.5 is \" << larger(1.5, 2.5) << std::endl;\r\n\tstd::cout << \"Larger of 3.5 and 4.5 is \" << larger(3.5, 4.5) << std::endl;\r\n\r\n\t\/\/ explict template argument\r\n\tstd::cout << \"Larger of \" << a_long << \" and 9.5 is \"\r\n          << larger<double>(a_long, 9.5) << std::endl;   \/\/ Outputs 9.5\r\n  \r\n}\r\n\r\n\/\/ Template for functions to return the larger of two values\r\ntemplate <typename T> T larger(T a, T b)\r\n{\r\n    return a > b ? a : b;\r\n}\r\n\r\n\/\/ Specialization of the template\r\ntemplate <> long* larger<long*>(long* a, long* b)\r\n{\r\n  return *a > *b ? a : b;\r\n}\r\n<\/pre>\n<span id=\"Lamda_Expressions\"><h2>Lamda Expressions<\/h2><\/span>\n<p>* A lamda expression is an anonymouse function<br \/>\n* Mainly used to pass a function as argument to another function<br \/>\n- it can access variables that exist in the enclosing scope where it is defined so an alternative to function pointer<br \/>\n* [], called lamda introducer, signifies a lamda expression<\/p>\n<pre lang=\"cpp\">\r\n\/\/ define a lamda expression\r\n[] (double value) { return value*value*value; }\r\n\r\n\/\/ specify return type\r\n[] (double value) -> double { return value*value*value; }\r\n\r\n\/\/ execute lamda expression and assign result to a variable\r\ndouble cube {};\r\ncube = [] (double value) -> double { return value*value*value; }(3.5);   \/\/ 42.875\r\n\r\n\/\/ Use lamda expression to initialize a variable\r\ncube {[] (double value) -> double { return value*value*value; }(3.5)};   \/\/ 42.875\r\n\r\n\/\/ Assign lamda expression to a variable\r\nauto cube = [] (double value) -> double { return value*value*value; };\r\n\r\n<\/pre>\n<p>* Passing a lamda expression to a function<\/p>\n<pre lang=\"cpp\">\r\n#include <iostream>\r\n#include <vector>\r\n#include <functional>\r\n\r\n\/\/ Define a function template that accept a function as argument\r\n\/\/ F type matches any function that accepts double as argument and returns double\r\ntemplate <typename F>\r\nstd::vector<double>& change(std::vector<double>& vec, F func){\r\n\tfor (auto& x : vec){\r\n\t\tx = func(x);\r\n\t}\r\n\treturn vec;\r\n}\r\n\r\n\/\/ Same as using function pointer\r\nstd::vector<double>& change2(std::vector<double>& vec, double(*func)(double)){\r\n\tfor (auto& x : vec){\r\n\t\tx = func(x);\r\n\t}\r\n\treturn vec;\r\n}\r\n\r\n\/\/ Same but using std::function template type\r\nstd::vector<double>& change3(std::vector<double>& vec, std::function<double(double)> fun)\r\n{\r\n  for (auto& x : vec)\r\n    x = fun(x);\r\n\r\n  return vec;\r\n}\r\n\r\nint main(){\r\n\t\/\/ Define cube lamda expression\r\n\tauto cube = [](double value) -> double {return value*value*value;};\r\n\t\r\n\t\/\/ Define average lamda expression\r\n\tauto average = [](const std::vector<double>& v) -> double{\r\n\t\tdouble sum{};\r\n\t\tfor (auto x : v){\r\n\t\t\tsum += x;\r\n\t\t}\r\n\t\treturn sum \/ v.size();\r\n\t};\r\n\t\r\n\tstd::vector<double> data {1.5, 2.5, 3.5, 4.5, 5.5};\r\n\tstd::cout << \"Average of values in data is \" << average(data) << std::endl;\r\n\r\n\t\/\/ Using function template and passing in lamda expression as function argument\r\n\tchange(data, [] (double x){return (x + 1.0)*(x + 2.0);});\r\n\tstd::cout << \"Average of changed values in data is \" << average(data) << std::endl;\r\n\t\r\n\t\/\/ Using function template and passing in cube lamda expression as function argument\r\n\tstd::cout << \"Average of cubes of values in data is \" << average(change3(data, cube)) << std::endl;\r\n}\r\n<\/pre>\n<p>* Lamda function capture clause<\/p>\n<pre lang=\"cpp\">\r\n\/\/ []: stateless lambda expression\r\n\/\/ lambda exp body cannot access any variables in its enclosing scope\r\n[] (double value) { return value*value*value; }\r\n\r\n\/\/ [=]: lambda exp body can access all variable values in its enclosing scope\r\n\/\/ cannot change variable values though\r\nstd::vector<double> data {1.5, 2.5, 3.5, 4.5, 5.5};\r\ndouble factor {10.0};\r\nchange(data, [=](double x){ return factor*x; }); \/\/ can access factor by value; cannot change factor's value\r\nstd::cout << \"The values in data are now:\\n\"\r\nfor(const auto&#038; x : data)\r\n  std::cout << \" \" << x;\r\nstd::cout << std::endl;\r\n\r\n\/\/[&#038;]: same as [=] but can change variable values\r\nchange(data, [&#038;](double x) { \r\n\tfactor += 2.0; \/\/ factor value can be changed here\r\n    return factor*x; }\r\n);\r\n\r\n\/\/[&#038;var]: same as [&#038;] but only var value can be changed\r\nchange(data, [&#038;factor](double x) { \r\n\tfactor += 2.0; \/\/ factor value can be changed here, all other variables cannot be chagned\r\n    return factor*x; }\r\n);\r\n\r\n\/\/[=, &#038;var]: only var value can be changed, all other variables can be accessed by values\r\nchange(data, [=, &#038;factor](double x) { \r\n\tfactor += 2.0; \/\/ factor value can be changed here, all other variables cannot be chagned\r\n    return factor*x; }\r\n);\r\n\r\n\/\/[&#038;, var]: all variables can be changed, var can only be accessed by value\r\nchange(data, [&#038;, factor](double x) { \r\n\tfactor += 2.0; \/\/ factor value can be changed here, all other variables cannot be chagned\r\n    return factor*x; }\r\n);\r\n<\/pre>\n<span id=\"Preprocessing_Directives\"><h2>Preprocessing Directives<\/h2><\/span>\n<p>* Translation unit: each source file + included header files<br \/>\n* Translation unit -compiler-&gt; object file -linker-&gt; executable file<br \/>\n* One definition rule: each variable, function, class type, enumeration type, or template in a translation unit must only be defined once.<\/p>\n<span id=\"Linkage_for_a_Name\"><h3>Linkage for a Name<\/h3><\/span>\n<p>* Internal linkage: can be accessed from anywhere within the same translation unit but NOT outside, e.g. global scope const var<\/p>\n<pre lang=\"cpp\">\r\nconst double pi {3.14159265};\r\n<\/pre>\n<p>* External linkage: can be accessed from another translation unit in addition to the one in which it is defined<br \/>\n* No linkage: can be accessed from within the scope that applies to the name, e.g. names defined within a block.<\/p>\n<pre lang=\"cpp\">\r\nextern const double pi {3.14159265};\r\n<\/pre>\n<p>* Access variable name defined outside current translation unit:<\/p>\n<pre lang=\"cpp\">\r\nextern double pi; \/\/ pi has been declared outside current translation unit already but we want to use it here\r\n<\/pre>\n<span id=\"Preprocessing_Source_Code\"><h3>Preprocessing Source Code<\/h3><\/span>\n<pre lang=\"cpp\">\r\n#include\r\n\t#include <iostream> \/\/ iostream header contents are included\r\n\t#include \"myheader.h\" \/\/ include myheader.h file in the current directory\r\n\t\r\n#define\r\n\t#define BLACK WHITE \/\/ Global replacement of BLACK with WHITE in source code\r\n\t#define BLACK \/\/ Global removal of BLACK from source code\r\n\r\n#undef\r\n\t#undef BLACK \/\/ Stop global replacements of BLACK\r\n\r\n#if\r\n#elif\r\n#else\r\n#endif\r\n\r\n#if defined \r\n\/\/ Same as:\r\n#ifdef\r\n\r\n#if !defined\r\n\/\/ Same as:\r\n#ifndef\r\n\r\n\/\/ Usage:\r\n#ifndef MYHEADER_H\r\n#define MYHEADER_H\r\n#include \"myheader.h\"\r\n#endif\r\n\r\n#line\r\n#error\r\n#pragma\r\n<\/pre>\n<span id=\"Using_Header_Files\"><h3>Using Header Files<\/h3><\/span>\n<p>* Ex10_01.h<\/p>\n<pre lang=\"cpp\">\r\n#include <string>\r\n#ifndef EX10_01_H\r\n#define EX10_01_H\r\nnamespace data\r\n{\r\n  extern const double pi {3.14159265};\r\n  extern const std::string days[] {\r\n                           \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\r\n                           \"Thursday\", \"Friday\", \"Saturday\"\r\n                                     };\r\n}\r\n#endif\r\n<\/pre>\n<p>* Ex10_01.cpp<\/p>\n<pre lang=\"cpp\">\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include \"Ex10_01.h\" \/\/ Include the header file\r\n\r\nint main()\r\n{\r\n  std::cout << \"pi has the value \" << data::pi << std::endl;\r\n  std::cout << \"The second day of the week is \" << data::days[1] << std::endl;\r\n}\r\n<\/pre>\n<span id=\"Classes\"><h2>Classes<\/h2><\/span>\n<p>* Syntax<\/p>\n<pre lang=\"cpp\">\r\nclass ClassName\r\n{\r\n  private:\r\n  \/\/ Code that specifies members that are not accessible from outside the class\r\n\r\n  protect:\r\n  \/\/ Code that specifies members that are accessible from subclasses\r\n  \r\n  public:\r\n  \/\/ Code that specifies members that are accessible from outside the class\r\n}; \/\/ Note the semicolon here!\r\n<\/pre>\n<p>* Constructor<\/p>\n<pre lang=\"cpp\">\r\n<\/pre>\n<p>- using the explicit keyword with constructors that have a single parameter to prevent implicit conversions from the parameter type to the class type<\/p>\n<pre lang=\"cpp\">\r\nclass Cube\r\n{\r\npublic:\r\n  double side;\r\n\r\n  explicit Cube(double side);               \/\/ Explicit constructor\r\n  double volume();                          \/\/ Calculate volume of a cube\r\n  bool compareVolume(Cube aCube);           \/\/ Compare volume of a cube with another\r\n};\r\n<\/pre>\n<p>* Destructor<\/p>\n<pre lang=\"cpp\">\r\n~Cube() {\r\n  \/\/ Cleanup...\r\n}\r\n<\/pre>\n<p>* Accessing member of a class using pointer<\/p>\n<pre lang=\"cpp\">\r\na->b\r\n\/\/ is equivalent to:\r\n(*a).b\r\n<\/pre>\n<p>* this pointer<\/p>\n<pre lang=\"cpp\">\r\ndouble Box::volume()\r\n{\r\n  return this->length * this->width * this->height;\r\n}\r\n<\/pre>\n<p>* Static members of a class<\/p>\n<p>* Pointers and references to class objectds<\/p>\n<p>* Using Pointers as class members<\/p>\n<p>* Example<br \/>\n- Box.h<\/p>\n<pre lang=\"cpp\">\r\n#ifndef BOX_H\r\n#define BOX_H\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\nclass Box {\r\n\t\/\/ Private memebers\r\n\tprivate:\r\n\t\tdouble length {1.0};\r\n\t\tdouble width {1.0};\r\n\t\tdouble height {1.0};\r\n\t\r\n\t\/\/ Public members\r\n\tpublic:\r\n\t\t\/\/ ======================= Constructors\r\n\t\t\/\/ Default constructor\r\n\t\tBox() {}\r\n\t\t\r\n\t\t\/\/ Using constructor initialization list\r\n\t\tBox(double lv, double wv, double hv): \r\n\t\t\tlength{lv}, width {wv}, height {hv} {}\r\n\t\t\r\n\t\t\/\/ Copy constructor, use const so we cannot modify object to be copied\r\n\t\tBox (const Box& box) {\r\n\t\t\tlength = box.length;\r\n\t\t\twidth = box.width;\r\n\t\t\theight = box.height;\r\n\t\t}\r\n\r\n\t\t\/\/ ======================= Getters and setters\r\n\t\t\/\/ Getters\r\n\t\tdouble getLength() {return length;}\r\n\t\tdouble getWidth()  {return width;}\r\n\t\tdouble getHeight() {return height;}\r\n\t\t\r\n\t\t\/\/ Setters\r\n\t\tvoid setLength(double lv) { if(lv > 0) length = lv;}\r\n\t\tvoid setWidth(double wv)  { if(wv > 0) width = wv;}\r\n\t\tvoid setHeight(double hv) { if(hv > 0) height = hv; }\r\n\r\n\t\t\/\/ ======================= Methods\r\n\t\tdouble volume() const {\r\n\t\t\treturn length * width * height;\r\n\t\t}\r\n\t\t\r\n\t\tint compare (const Box& box) {\r\n\t\t\tif (volume() < box.volume()) \r\n\t\t\t\treturn -1;\r\n\t\t\t\t\r\n\t\t\tif (volume() == box.volume())\r\n\t\t\t\treturn 0;\r\n\t\t\t\t\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\t\r\n\t\tvoid listBox() {\r\n\t\t\tstd::cout << \" Box(\" \r\n\t\t\t\t<< std::setw(2) << length << \",\"\r\n\t\t\t\t<< std::setw(2) << width << \",\"\r\n\t\t\t\t<< std::setw(2) << height << \")\";\r\n\t\t}\r\n\t\t\r\n};\r\n#endif\r\n<\/pre>\n<p>- Testbox.cpp<\/p>\n<pre lang=\"cpp\">\r\n#include <iostream>\r\n#include \"Box.h\"\r\n\r\nint main(){\r\n\tconst Box box1 {2.0, 3.0, 4.0}; \r\n\t\r\n\tstd::cout << \"Volume: \" << box1.volume() << std::endl;\r\n}\r\n<\/pre>\n<span id=\"Operator_Overloading\"><h2>Operator Overloading<\/h2><\/span>\n<p>* <\/p>\n<pre lang=\"cpp\">\r\n<\/pre>\n<span id=\"Inheritance\"><h2>Inheritance<\/h2><\/span>\n<span id=\"Polymorphism\"><h2>Polymorphism<\/h2><\/span>\n<span id=\"Runtime_Errors_and_Exception\"><h2>Runtime Errors and Exception<\/h2><\/span>\n<span id=\"Class_Templates\"><h2>Class Templates<\/h2><\/span>\n<span id=\"File_IO\"><h2>File IO<\/h2><\/span>\n<span id=\"References_1\"><h2>References<\/h2><\/span>\n<p>* Beginning C++ by Ivor Horton<br \/>\n* <a href=\"https:\/\/github.com\/Apress\/beg-cpp\">Book source code<\/a><br \/>\n* <a href=\"http:\/\/www.cplusplus.com\/reference\/\">Standard C++ Library reference<\/a><br \/>\n* <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/header\">C++ Standard Library header files<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Overview * Latest standard: C++14 * Compile command with Visual Studion command line cl \/EHsc test.cpp * Comments (same as Java and C#): \/\/ this is a comment \/* this is another comment *\/ * Preprocessing directives and header files &hellip; <a href=\"https:\/\/jianmingli.com\/wp\/?p=12086\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[11],"tags":[556],"class_list":["post-12086","post","type-post","status-publish","format-standard","hentry","category-cpp","tag-c"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8cRUO-38W","_links":{"self":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts\/12086","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=12086"}],"version-history":[{"count":2,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts\/12086\/revisions"}],"predecessor-version":[{"id":12089,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts\/12086\/revisions\/12089"}],"wp:attachment":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=12086"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=12086"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=12086"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}