ccourse 140618093931-phpapp02

Post on 16-Apr-2017

116 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

C++ Introductory Course

- By Dennis Chang

C++ Course Outline

OOP Concepts Basic C++ I/O Functions Pointers, addresses and variables Classes and Objects Overloading Templates

C++ Course Outline

Exception Handling Data Structures Introduction to STL

OOP Concept

What is OOP?A program implementation style thatsupport the following concepts:

– Abstraction– Encapsulation– Inheritance– Polymorphism

OOP Concept (Data Abstraction)

The ability of packing data together with functions, that allows you to create a new data type.

OOP Concept (Inheritance)

Inheritance is the process whereby one object acquires characteristics from one or more objects.

OOP Concept (Composition)

Composition provides the facility for creating a new object from two or more objects.

OOP Concept (Encapsulation)

Encapsulation is the property of being a self-contained unit.

Data hidingThe encapsulated unit can be used withoutregard how it works internally.

OOP Concept (Polymorphism)

Polymorphism refers to the same name taking many forms.

See Virtual Functions at a later section.

OOP Concepts (Keywords in C++)class deletefriend protectedhandle publicinline templatenew thisoperator virtualprivate

Basic C++ I/O

cin, tied to standard input. cout, tied to standard output.

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;}

Basic C++ I/O

Examples of C++ I/O

The output is:

Hello WorldPlease enter a number : 5The number is 5

Basic C++ I/O

Compare to C built-in library functions:– printf, scanf functions.– Differences between cin/cout and

printf/scanf.

Functions

Declaring functionsreturn_type function_name ( [type][parameter1] ,[type][parameter2], ….)

Defining functionsreturn_type function_name ([type][parameter1],[type][parameter2], ….){

statements;}

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.

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

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

Classes and Objects

Access Control– Private (Only by own member functions)– Protected (By own and child functions)– Public (By all)

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

Classes and Objects

Destructor– member function (~classname)– automatically invoked when an object goes

out of scope– cannot take arguments– does not have return type

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 initialisationint length; // Data memberchar *content; // Data member

} ;

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

Classes and Objects

Example of Class declaration:class String{public:

String(char *aString=0); //Constructor~String(); //Destructorint GetLength() const; //Member functionconst char* GetContent() const; //Member functionvoid SetContent(const char* aString) //Member function

private:int m_nlength; //Data memberchar* m_szContent; //Data member

};

Classes and Objects

Examples of Member functions implementation:

int String::GetLength() const{

return m_nLength;}

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;

}

Classes and Objects

Derived classes:class subClassName : public baseClassName{

//private member declarationspublic:

//public member declarations};

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.

Classes and Objects

this Pointer– Example:

void Date::setMonth( int mn )

{

month = mn; // These three statements

this->month = mn; // are equivalent

(*this).month = mn;

}

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; }

Classes and Objects

this Pointerprivate:

int hour;int minute;int second;

};

main( ){

Time t;t.SetHour(18).SetMinute(30).SetSecond(20); //Concatenating member function calls

return 0;}

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.

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;

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!

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.

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

Classes and Objects

Friend Classes– Syntax:

class A { class B {private: class B can access…. the private area of

class Afriend class B; };};

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; };

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; };

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.

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

Pointers, addresses and variables

Indirection– Accessing the value at the address held by

a pointer.– The indirection operator (*) is also called

the dereference operator.

Pointers, addresses and variables

Examples of indirection:int nVariable = 5; int *pPointer = &nVariable;cout << *pPointer << endl;

Output :5

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;}

Pointers, addresses and variables

Pass by valuesvoid 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”;

}

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.

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.

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

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.

Pointers, addresses and variables

Memory Allocation/Deallocation– Keywords :

• For C :– malloc( ) and free().

• For C++ :– new and delete.

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);

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;

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.

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.

Pointers, addresses and variables

Keyword const– Examples:

int x=10, y=20;const int* pXPtr = &x; //Non-constant pointer, constant dataint* const pYPtr = &y; //Constant pointer, non-constant data

pXPtr = &y; //Legal*pXPtr = 20; //ErrorpYPtr = &x; //Error*pYPtr = 10; //Legal

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.

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.

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-RateB) For permanent commission based employee: Salary = Basic salary + CommissionC) For temporary worker, Salary = Number of hours worked * RateThe 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 ]

Overloading

Function Overloading:– A function can be reused with different

arguments and return type.– Eg. void print(char* szMessage) and void

print(int number)

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.

Overloading

Operator Overloading:– Example:class NumberClass {public:

//Overloading assignment operatorconst NumberClass& operator=(const NumberClass &);

private:int a;int b;int c;

};

Overloading

Operator Overloading:– Example (con’t):const NumberClass& NumberClass::operator=(const NumberClass& source){

a = source.a;b = source.b;c = source.c;

return *this;}

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;}

Overloading

Virtual functionExample :

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;

}

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.

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.

Templates

Provide a way to re-use source code.template <class Type> //Template Class declarationclass foo { public: int DummyFunc(); //rest of class…… };

template<class Type>int foo<Type>::DummyFunc( ) {….} //Implementation of member function

foo <float> ff; // Instantiationfoo <int> ii; //Another instance created

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.

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.

Exception handling

Syntaxtry { // code that may generate exceptions ( throw exceptions)} catch( type1 id1) { //handle exceptions of type1} catch(type2 id2) { //handle exceptions of type2

}

Exception handling

Examples:#include <iostream.h>

class Inner {public: Inner(); ~Inner();

void fun();}; class Outer {public:

Outer();~Outer();void fun();

};

Exception handling

Examples (Con’t):Inner::Inner(){ cout << "Inner constructor\n";}

Inner::~Inner(){ cout << "Inner destructor\n";}

void Inner::fun(){ cout << "Inner fun\n"; throw 1; //throw an exception cout << "This statement is not executed\n";}

Exception handling

Examples (Con’t):Outer::Outer(){ cout << "Outer constructor\n";} Outer::~Outer(){ cout << "Outer destructor\n";}

void Outer::fun(){ Inner in; cout << "Outer fun\n"; in.fun();}

Exception handling

Examples (Con’t):int main(){ Outer out; try { out.fun();

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;

}

Exception handling

Examples (Con’t):Generated output::

Outer constructor Inner constructor Outer fun Inner fun Inner destructor Exception 1 occurred

Outer destructor

Data Structures

Linked List

H QK ……..

First Ptr Last Ptr

Data Structures

Stacks

H

K

Q

LIFO

Data Structures

Queues

H K Q…………...

FIFO

Data Structures

Trees

C

DA

B

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 LengthInventoryNo Alpha 20 charactersPrice Numeric 9 decimal digitsSupplier Alpha 20 charactersDate Numeric 8 decimal digitsMin_SL Numeric 3 decimal digitsMaterials Alpha 10 charactersVoltage Numeric 3 decimal digitsMax_SL Numeric 3 decimal digitsPrice Numeric 5 decimal digitsStoragetemp 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:

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.]

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.

Introduction to STL

Standard Template Library Containers

– Objects that hold other objects. Eg. vector Algorithms

– Functions that act on Containers. Iterators

– Pointer-like objects.

Introduction to STL

Allocators– Manages memory allocation for a

container. STL Template class :

– vector, map, list, stack, deque, set.

Introduction to STL

Example : vector#include <iostream>#include <vector>using namespace std;

int main(){

vector<int> v(10); //Create a vector of length 10int i;

// Display original size of vcout << "Size = " << v.size() << endl;

// Assign values to elements of vectorfor(i=0; i < 10; i++)

v[i] = i;

Introduction to STL

// Display contents of vectorcout << "Current Contents :\n";for(i=0; i < v.size(); i++)

cout << v[i] << " ";cout << "\n\n";

// Expand the vectorcout << "Expanding vector\n";for(i=0; i < 5; i++)

v.push_back(i + 20);// Display current sizecout << "Size now = " << v.size() << endl;

// Display contents of vectorcout << "Current Contents :\n";for(i=0; i < v.size(); i++)

cout << v[i] << " ";cout << "\n\n";

Introduction to STL

// Change contents of vectorfor(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;}

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 10vector<int>::iterator p; //Create an iteratorint i;

// Assign values to elements of vectorp = v.begin();i=0;

Introduction to STL

while(p != v.end()){*p = i; //assign i to v through pp++; //advance the iteratori++;}

// Display contents of vectorcout << "Original Contents :\n";p = v.begin();while(p != v.end()){cout << *p << " ";p++;}

cout << "\n\n";

Introduction to STL

// change contents of vectorp = v.begin();while(p != v.end()){*p = *p * 2;p++;}

// Display contents of vectorcout << "Modified Contents :\n";p = v.begin();while(p != v.end()){cout << *p << " ";p++;}cout << endl;return 0;

}

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.]

References

C++ How To Program STL Programming from the ground up. http://www.4p8.com/eric.brasseur/

cppcen.html MSDN Library

top related