Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

C++ Programming Course


Published on

Course notes on C++ Programming that I prepared for the training of other software engineers.

Published in: Software, Technology, Business
  • Be the first to comment

C++ Programming Course

  1. 1. C++ Introductory Course - By Dennis Chang
  2. 2. C++ Course Outline OOP Concepts Basic C++ I/O Functions Pointers, addresses and variables Classes and Objects Overloading Templates
  3. 3. C++ Course Outline Exception Handling Data Structures Introduction to STL
  4. 4. OOP Concept What is OOP? A program implementation style that support the following concepts: – Abstraction – Encapsulation – Inheritance – Polymorphism
  5. 5. OOP Concept (Data Abstraction) The ability of packing data together with functions, that allows you to create a new data type.
  6. 6. OOP Concept (Inheritance) Inheritance is the process whereby one object acquires characteristics from one or more objects.
  7. 7. OOP Concept (Composition) Composition provides the facility for creating a new object from two or more objects.
  8. 8. OOP Concept (Encapsulation) Encapsulation is the property of being a self-contained unit. Data hiding The encapsulated unit can be used without regard how it works internally.
  9. 9. OOP Concept (Polymorphism) Polymorphism refers to the same name taking many forms. See Virtual Functions at a later section.
  10. 10. OOP Concepts (Keywords in C++) class delete friend protected handle public inline template new this operator virtual private
  11. 11. Basic C++ I/O cin, tied to standard input. cout, tied to standard output.
  12. 12. Basic C++ I/O Examples of C++ I/O #include <iostream.h> main() { int nTemp; cout << “Hello World”; cout << “Please enter a number : “; cin >> nTemp; cout << “ The number is “ << nTemp << endl; return 0; }
  13. 13. Basic C++ I/O Examples of C++ I/O The output is: Hello World Please enter a number : 5 The number is 5
  14. 14. Basic C++ I/O Compare to C built-in library functions: – printf, scanf functions. – Differences between cin/cout and printf/scanf.
  15. 15. Functions Declaring functions return_type function_name ( [type][parameter1] , [type][parameter2], ….) Defining functions return_type function_name ([type][parameter1], [type][parameter2], ….) { statements; }
  16. 16. Functions Inline functions – The qualifier inline before a function’s return type in the function definition “advises” the compiler to generate a copy of the function’s code in place to avoid a function call. – Reduce execution time, but increase program size. – Why not use Macros ? • Macros don’t really obey the rules of C++ and therefore can introduce problems.
  17. 17. Classes and Objects What are Classes ? – A user-defined type – A collection of variables combined with a set of related functions – An extension of the concepts “struct” – Mechanism used in C++ for data abstraction
  18. 18. Classes and Objects What are Classes ? – A C++ class has the following associated attributes: • Access Control • Constructors and Destructors • A collection of data members • A collection of member functions • An associated class tag name
  19. 19. Classes and Objects Access Control – Private (Only by own member functions) – Protected (By own and child functions) – Public (By all)
  20. 20. Classes and Objects Constructor – member functions with the same name as the class (classname) – support the automatic initialisation of objects at their point of declaration – can take arguments – do not have return types
  21. 21. Classes and Objects Destructor – member function (~classname) – automatically invoked when an object goes out of scope – cannot take arguments – does not have return type
  22. 22. Classes and Objects Data Members – Data members are states or attributes of an object – An Example: class String { private: int flag = 0; // error !!! no explicit initialisation int length; // Data member char *content; // Data member } ;
  23. 23. Classes and Objects Member Functions – Member functions are public interface – Member functions have full access privilege to the public, protected and private members of the class – Member functions are defined within the scope of their class
  24. 24. Classes and Objects Example of Class declaration: class String { public: String(char *aString=0); //Constructor ~String(); //Destructor int GetLength() const; //Member function const char* GetContent() const; //Member function void SetContent(const char* aString) //Member function private: int m_nlength; //Data member char* m_szContent; //Data member };
  25. 25. Classes and Objects Examples of Member functions implementation: int String::GetLength() const { return m_nLength; }
  26. 26. Classes and Objects Object Instantiation #include “String.h” main() { /* Create object using memory from stack */ String S1(“Hello”); /* Create object using memory from heap */ String* pS1; pS1 = new String(“Hello”); cout << pS1->GetContent() << endl; }
  27. 27. Classes and Objects Derived classes: class subClassName : public baseClassName { //private member declarations public: //public member declarations };
  28. 28. Classes and Objects this Pointer – The this pointer is a pointer accessible only within the member functions of a class, struct, or union type. – It points to the object for which the member function is called. – Static member functions do not have a this pointer.
  29. 29. Classes and Objects this Pointer – Example: void Date::setMonth( int mn ) { month = mn; // These three statements this->month = mn; // are equivalent (*this).month = mn; }
  30. 30. Classes and Objects this Pointer – Concatenating member function calls: • Example: class Time { public: Time(int hour=0, int minute=0, int second=0); //Default constructor Time& SetHour(int hour) { m_hour = hour; return *this; } Time& SetMinute(int minute) { m_minute = minute; return *this; } Time& SetSecond(int second) { m_second = second; return *this; }
  31. 31. Classes and Objects this Pointer private: int hour; int minute; int second; }; main( ) { Time t; t.SetHour(18).SetMinute(30).SetSecond(20); //Concatenating member function calls return 0; }
  32. 32. Classes and Objects Keyword static – In C++, when modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all the instances of the class. – When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.
  33. 33. Classes and Objects Keyword static (Example) class SavingsAccount { public: static void setInterest( float newValue ) // Member function { currentRate = newValue; } // that accesses only static members private: char name[30]; float total; static float currentRate; // One copy of this member is shared among // all instances of SavingsAccount }; // Static data members must be initialized at file scope, even if private. float SavingsAccount::currentRate = 0.00154;
  34. 34. Classes and Objects Friend Classes – A class may name another function or another class as its friend. That gives the named function the right to access all private features. – This is a dangerous mechanism and shouldn’t be used unless necessary!
  35. 35. Classes and Objects Friend Classes – Friendship is not mutual unless explicitly specified as such. – Friendship is not inherited. – Friendship is not transitive. Therefore, if class A is a friend of class B, and class B is a friend of class C, we cannot infer that class C is a friend of class A.
  36. 36. Classes and Objects Friend Classes – Common Usage: • to allow nested classes to access the private members of the surrounding class; • to access the private members of other nested classes; • to allow the surrounding class to access the private members of nested classes. • Example: In linked list, the list and node objects
  37. 37. Classes and Objects Friend Classes – Syntax: class A { class B { private: class B can access …. the private area of class A friend class B; }; };
  38. 38. Classes and Objects Friend Classes – Examples: class Surround { public: class FirstWithin { friend class Surround; //Allows Surround to access private members public: int getValue(); private: static int variable; };
  39. 39. Classes and Objects Friend Classes – Examples (Con’t): int getValue() { // inline member function of Surround FirstWithin::variable = SecondWithin::variable; return (variable); } private: class SecondWithin { friend class Surround; public: int getValue(); private: static int variable; }; static int variable; };
  40. 40. Pointers, addresses and variables A pointer is a variable that holds a memory address. It is important to distinguish between a pointer, the address that the pointer holds,and the value at the address held by the pointer. This is the source of much of the confusion about pointers.
  41. 41. Pointers, addresses and variables Example : int nVariable = 5; //declare a variable of type integer and //assign a value 5 to it. int *pPointer = &nVariable; //declare a pointer variable that //holds the address of an integer, //and assigns the address of the //variable nVariable to it
  42. 42. Pointers, addresses and variables Indirection – Accessing the value at the address held by a pointer. – The indirection operator (*) is also called the dereference operator.
  43. 43. Pointers, addresses and variables Examples of indirection: int nVariable = 5; int *pPointer = &nVariable; cout << *pPointer << endl; Output : 5
  44. 44. Pointers, addresses and variables Pass by values #include <iostream.h> void swap(int x, int y); int main() { int x=5, y=10; cout << “Main. Before swap, x:” << x << “ y:” << y << “n”; swap(x,y); cout << “Main. After swap, x:” << x << “ y:” << y << “n”; return 0; }
  45. 45. Pointers, addresses and variables Pass by values void swap(int x, int y) { int temp; cout << “Swap. Before swap, x :” << x << “ y:” << y << “n”; temp=x; x=y; y=temp; cout << “Swap. After swap, x:” << x << “ y:” << y << “n”; }
  46. 46. Pointers, addresses and variables Pass by Reference – Instead of passing values as parameters, address of the arguments are passed. – Can use reference arguments (& ampersand) or pointer arguments.
  47. 47. Pointers, addresses and variables Pass by Reference – What is references ? • Used as aliases for other variables. • No space reserved for the alias. • Operations performed on the alias (ie the reference) are actually performed on the variable itself. • Reference variables must be initialized.
  48. 48. Pointers, addresses and variables Pass by Reference – What is reference ? • Examples: int nCount = 1; int& nRefCount = nCount; //Create an alias for nCount ++nRefCount; //Increment nCount
  49. 49. Pointers, addresses and variables Return-by-Value vs Return-by-Reference – Return references can be dangerous. – A local variable in a function is discarded when the function terminates. When returning a reference to a variable declared in the called function, the program behavior would be unpredictable.
  50. 50. Pointers, addresses and variables Memory Allocation/Deallocation – Keywords : • For C : – malloc( ) and free(). • For C++ : – new and delete.
  51. 51. Pointers, addresses and variables Memory Allocation/Deallocation – C Examples • For memory allocation. Example: TypeName *typeNamePtr; typeNamePtr = malloc(sizeof(TypeName)); • For memory deallocation. Example: free(typeNamePtr);
  52. 52. Pointers, addresses and variables Memory Allocation/Deallocation – C++ Examples • For memory allocation. Example: int* pnPtr=0; char* pcChar=0; pnPtr = new int; //Allocate space for pointer //variable pcChar = new char[20] //Allocate space for 20 char. • For memory deallocation. Example : delete pnPtr; delete[ ] pcChar;
  53. 53. Pointers, addresses and variables Memory Allocation/Deallocation – Notes: • Unlike new, malloc does not provide any method of initializing the block of memory allocated. • new/delete automatically invokes the constructor/destructor. • Do not mix new with free and malloc with delete.
  54. 54. Pointers, addresses and variables Keyword const – Non-constant pointer to constant data: • Pointer can points to other variable, but data to which it points can’t be modified. – Constant pointer to non-constant data: • Pointer always point to the same memory location, but data can be modified.
  55. 55. Pointers, addresses and variables Keyword const – Examples: int x=10, y=20; const int* pXPtr = &x; //Non-constant pointer, constant data int* const pYPtr = &y; //Constant pointer, non-constant data pXPtr = &y; //Legal *pXPtr = 20; //Error pYPtr = &x; //Error *pYPtr = 10; //Legal
  56. 56. Pointers, addresses and variables Keyword const – More Examples void String::SetContent(const char* aString) { if(m_szContent) { delete[] m_szContent; } m_szContent = new char[strlen(aString) + 1]; assert(m_szContent != 0); strcpy(m_szContent, aString); } Ensure the parameter is not changed inside the function.
  57. 57. Pointers, addresses and variables Keyword const – More Examples const char* String::GetContent() const { return m_szContent; } Ensure the member function does not modify any data members of the object. Reminder that the private data member m_pszString should not be modified from outside the member functions.
  58. 58. Tutorial 1 1. Write an object-oriented console application which allows the user to key in an employee’s data from the keyboard. Common data includes name, staff_id, designation and department. Employees of the company are made up of Permanent staff and temporary workers. The permanent staff is made up of salary-based and commission-based personnel. The application should query the user which type of employee he/she belongs to. Salary of different type of employees are computed in different ways: A) For permanent salary based employee: Salary = Basic salary + Hours of OT * OT-Rate B) For permanent commission based employee: Salary = Basic salary + Commission C) For temporary worker, Salary = Number of hours worked * Rate The program should be able to display all information of the employee on the screen after the user keyed in required data. (Salary is to be computed, not entered by the user) 2. Write a program to let user enter two numbers and swap them. The program should consist of a main function and a swap function. After the swapping, the main function should be able to display on the screen the result. [Hint : Use pointers ]
  59. 59. Overloading Function Overloading: – A function can be reused with different arguments and return type. – Eg. void print(char* szMessage) and void print(int number)
  60. 60. Overloading Operator Overloading: – Allow existing operators to be overloaded so that when these operators are used with class objects, the operators have meaning appropriate to the new types.
  61. 61. Overloading Operator Overloading: – Example: class NumberClass { public: //Overloading assignment operator const NumberClass& operator=(const NumberClass &); private: int a; int b; int c; };
  62. 62. Overloading Operator Overloading: – Example (con’t): const NumberClass& NumberClass::operator=(const NumberClass& source) { a = source.a; b = source.b; c = source.c; return *this; }
  63. 63. Overloading Operator Overloading: – Example (con’t): main() { NumberClass A(1,1,1), B(2,2,2); A=B; // Invoked the overloaded assignment function return 0; }
  64. 64. Overloading Virtual function Example : class Base { public: virtual void print() { cout << “nThis is from Base Class” << endl; } }; class Derive : public Base { public: void print() { cout << “nThis is from Derive Class” << endl; } }; main() { Base* GenericClass = 0; GenericClass = new Derive; Derive->print(); delete GenericClass; }
  65. 65. Overloading Pure Virtual function – A virtual function which has no implementation. – Written as virtual prototype = 0; – All derived class must provide their own definition. – An abstract class is a class that contains pure virtual function.
  66. 66. Tutorial 2 1. Develop class Polynomial. The internal representation of a Polynomial is an array of terms. Each term contains a coefficient and an exponent. The term 2x4 has a coefficient of 2 and an exponent of 4. Develop a full class containing proper constructor and destructor functions as well as set and get functions. The class should also provide the following overloaded operator capabilities : A) Overload the addition operator (+) to add two Polynomials. B) Overload the subtraction operator (-) to subtract two Polynomials. C) Overload the assignment operator to assign one Polynomial to another. D) Overload the multiplication operator (*) to multiply two Polynomials.
  67. 67. Templates Provide a way to re-use source code. template <class Type> //Template Class declaration class foo { public: int DummyFunc(); //rest of class…… }; template<class Type> int foo<Type>::DummyFunc( ) {….} //Implementation of member function foo <float> ff; // Instantiation foo <int> ii; //Another instance created
  68. 68. Exception handling Overview – Exceptions occur when a program executes abnormally due to conditions outside the program's control, such as low memory or I/O errors. – The order in which catch handlers appear is significant, because handlers for a given try block are examined in order of their appearance.
  69. 69. Exception handling Overview – After a matching catch handler is found, subsequent handlers are not examined. – As a result, an ellipsis (…) catch handler must be the last handler for its try block.
  70. 70. Exception handling Syntax try { // code that may generate exceptions ( throw exceptions) } catch( type1 id1) { //handle exceptions of type1 } catch(type2 id2) { //handle exceptions of type2 }
  71. 71. Exception handling Examples: #include <iostream.h> class Inner { public: Inner(); ~Inner(); void fun(); }; class Outer { public: Outer(); ~Outer(); void fun(); };
  72. 72. Exception handling Examples (Con’t): Inner::Inner() { cout << "Inner constructorn"; } Inner::~Inner() { cout << "Inner destructorn"; } void Inner::fun() { cout << "Inner funn"; throw 1; //throw an exception cout << "This statement is not executedn"; }
  73. 73. Exception handling Examples (Con’t): Outer::Outer() { cout << "Outer constructorn"; } Outer::~Outer() { cout << "Outer destructorn"; } void Outer::fun() { Inner in; cout << "Outer funn";; }
  74. 74. Exception handling Examples (Con’t): int main() { Outer out; try {; cout << "nThis line will also not be executed" << endl; } catch (int i) { cout << "Exception " << i << " occurred" << endl; } catch (...) { //ellipsis handler, handle any type of exceptions cout << ”Exception occurred" << endl; } return 0; }
  75. 75. Exception handling Examples (Con’t): Generated output:: Outer constructor Inner constructor Outer fun Inner fun Inner destructor Exception 1 occurred Outer destructor
  76. 76. Data Structures Linked List H Q K …….. First Ptr Last Ptr
  77. 77. Data Structures Stacks H K Q LIFO
  78. 78. Data Structures Queues H K Q…………... FIFO
  79. 79. Data Structures Trees C D A B
  80. 80. Tutorial 3 1. Consider the following abstractions on inventory in a supermarket (represented as classname [structure : behavior}) with base class: Inventory {InventoryNo, price, supplier, date: entry, display} and two derived classes : Durable{min_shelf_life, materials, voltagetype : entry, display} and NonDurable {max_shelf_life, price, storagetemp : entry, display} Assume that you are given the following specifications for the attributes listed above: Field Name Field Type Field Length InventoryNo Alpha 20 characters Price Numeric 9 decimal digits Supplier Alpha 20 characters Date Numeric 8 decimal digits Min_SL Numeric 3 decimal digits Materials Alpha 10 characters Voltage Numeric 3 decimal digits Max_SL Numeric 3 decimal digits Price Numeric 5 decimal digits Storagetemp Numeric 3 decimal digits The classes should have at least entry() and display() member functions to collect inputs and display data items of attributes through keyboard and screen respectively. Suppose we need one list class to hold the objects of the above classes. The list class should have the following member functions:
  81. 81. Tutorial 3 Sort_add() to append a new Durable or NonDurable object to the ordered list which uses the InventoryNo as the key to maintain the objects of the list in a descending sequence. Remove() to remove one Durable or NonDurable object from the list according to the InventoryNo. Display() to display all the objects in the list. Merge() to merge a durable list with a NonDurable list: If 11 and 12 are lists, merge(11,12) is to create a new list formed by appending 12 to the end of 11. A destructor: to de-allocate all memories. Write an OO program in C++ to: Declare necessary classes based on the specifications given above. Each node in the class list is an object of Durable or NonDurable classes. Create two ordered lists. One is for holding objects of Durable and one for objects of NonDurable. Allow each object data items to be set through the keyboard. Create a heterogeneous list by copying and merging the two lists: Durable and NonDurable into one. Remove an object from the heterogeneous list by providing the InventoryNo. Display all attributes of objects in the heterogeneous list on screen. De-allocate all memories in the list. [A list that can hold non-identical items is known as heterogeneous linked list.]
  82. 82. Tutorial 4 1. Create a new abstract data type called Dynamic Array. This class contains an array as its attribute. The array should be able to “grow” and “shrinks” automatically when the user choose to insert or remove an item from the array. This class should be implemented as a template class so that it can be used to hold an array of any data types. Tasks: A) Declare a template class DynamicArray. B) The class should have an array as its attribute. It should also contain a data member m_nSize indicating the current size of the array. C) The array needs not to be sorted. However, the class should have the capability of inserting and removing any items from the array. The size of the array should be able to “grow” and “shrink” accordingly. Take care of any possible memory leaks. D) The class should also include a member function for computing : (I) The sum of all items in the array (II)The largest and smallest number in the array E) Provide a user interface (console-based) to test out the class. F) Test out the template class using integer and float as the array types.
  83. 83. Introduction to STL Standard Template Library Containers – Objects that hold other objects. Eg. vector Algorithms – Functions that act on Containers. Iterators – Pointer-like objects.
  84. 84. Introduction to STL Allocators – Manages memory allocation for a container. STL Template class : – vector, map, list, stack, deque, set.
  85. 85. Introduction to STL Example : vector #include <iostream> #include <vector> using namespace std; int main() { vector<int> v(10); //Create a vector of length 10 int i; // Display original size of v cout << "Size = " << v.size() << endl; // Assign values to elements of vector for(i=0; i < 10; i++) v[i] = i;
  86. 86. Introduction to STL // Display contents of vector cout << "Current Contents :n"; for(i=0; i < v.size(); i++) cout << v[i] << " "; cout << "nn"; // Expand the vector cout << "Expanding vectorn"; for(i=0; i < 5; i++) v.push_back(i + 20); // Display current size cout << "Size now = " << v.size() << endl; // Display contents of vector cout << "Current Contents :n"; for(i=0; i < v.size(); i++) cout << v[i] << " "; cout << "nn";
  87. 87. Introduction to STL // Change contents of vector for(i=0; i < v.size(); i++) v[i] = -v[i]; cout << "Modified Contents :n"; for(i=0; i < v.size(); i++) cout << v[i] << " "; cout << endl; return 0; }
  88. 88. Introduction to STL Example of Iterator // Access the elements of a vector through an iterator. #include <iostream> #include <vector> using namespace std; int main() { vector<int> v(10); //Create a vector of length 10 vector<int>::iterator p;//Create an iterator int i; // Assign values to elements of vector p = v.begin(); i=0;
  89. 89. Introduction to STL while(p != v.end()) { *p = i; //assign i to v through p p++; //advance the iterator i++; } // Display contents of vector cout << "Original Contents :n"; p = v.begin(); while(p != v.end()) { cout << *p << " "; p++; } cout << "nn";
  90. 90. Introduction to STL // change contents of vector p = v.begin(); while(p != v.end()) { *p = *p * 2; p++; } // Display contents of vector cout << "Modified Contents :n"; p = v.begin(); while(p != v.end()) { cout << *p << " "; p++; } cout << endl; return 0; }
  91. 91. Tutorial 5 1. Implement a German-English Dictionary. The dictionary should have a console-based user interface that allows user to A) Insert a pair of German and English word into the dictionary. B) Enter a German word and search for it’s counterpart in English, and vice versa. (The relationship is One-to-One) C) Display a list of words (German and English) inside the dictionary sorted in alphabetical order (user can choose to sort the German words or English words). D) Remove a pair of words from the dictionary. E) Optional : [ Upon exiting the program, save the data inside the dictionary into a text file. Subsequent execution of the program will load the data from the text file into whatever designated data structures.]
  92. 92. References C++ How To Program STL Programming from the ground up. n.html MSDN Library