SlideShare a Scribd company logo
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 that
support 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 hiding
The encapsulated unit can be used without
regard 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 delete
friend protected
handle public
inline template
new this
operator virtual
private
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 World
Please enter a number : 5
The 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 functions
return_type function_name ( [type][parameter1] ,
[type][parameter2], ….)
Defining functions
return_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 initialisation
int length; // Data member
char *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(); //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
};
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 declarations
public:
//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 Pointer
private:
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 A
friend 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 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”;
}
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 data
int* const pYPtr = &y; //Constant pointer, non-constant data
pXPtr = &y; //Legal
*pXPtr = 20; //Error
pYPtr = &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-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 ]
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 operator
const 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 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;
}
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 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
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
Syntax
try {
// 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 constructorn";
}
Inner::~Inner()
{
cout << "Inner destructorn";
}
void Inner::fun()
{
cout << "Inner funn";
throw 1; //throw an exception
cout << "This statement is not executedn";
}
Exception handling
Examples (Con’t):
Outer::Outer()
{
cout << "Outer constructorn";
}
Outer::~Outer()
{
cout << "Outer destructorn";
}
void Outer::fun()
{
Inner in;
cout << "Outer funn";
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
Q
K
……..
First Ptr
Last Ptr
Data Structures
Stacks
H
K
Q
LIFO
Data Structures
Queues
H K Q…………...
FIFO
Data Structures
Trees
C
D
A
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 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:
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 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;
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";
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;
}
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;
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";
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;
}
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/cppce
n.html
MSDN Library

More Related Content

PDF
Deep C
Olve Maudal
 
PPTX
Function C programming
Appili Vamsi Krishna
 
PPTX
Basics of Java
Sherihan Anver
 
PPT
C++
Sunil OS
 
PPSX
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
PPTX
Intro to c++
temkin abdlkader
 
PDF
Constructors and Destructors
Dr Sukhpal Singh Gill
 
PPT
Operator Overloading
Nilesh Dalvi
 
Deep C
Olve Maudal
 
Function C programming
Appili Vamsi Krishna
 
Basics of Java
Sherihan Anver
 
Data types, Variables, Expressions & Arithmetic Operators in java
Javed Rashid
 
Intro to c++
temkin abdlkader
 
Constructors and Destructors
Dr Sukhpal Singh Gill
 
Operator Overloading
Nilesh Dalvi
 

What's hot (20)

PPT
OOP in C++
ppd1961
 
PPTX
Conditional statements
University of Potsdam
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PPSX
Complete C++ programming Language Course
Vivek Singh Chandel
 
PPTX
Iostream in c++
غزالة
 
PPTX
Polymorphism presentation in java
Ahsan Raja
 
PPTX
C functions
University of Potsdam
 
PPTX
C introduction by thooyavan
Thooyavan Venkatachalam
 
PPTX
C/C++ language Presentation
S.Saeed H
 
DOCX
Angular Interview Questions & Answers
Ratnala Charan kumar
 
PDF
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
PPTX
Function Pointer
Dr-Dipali Meher
 
PDF
Object-oriented Programming-with C#
Doncho Minkov
 
PPT
C++ Interview Questions
Kaushik Raghupathi
 
PPTX
Structure in c language
sangrampatil81
 
PPTX
Functions in c language
Tanmay Modi
 
PPTX
Unit 7. Functions
Ashim Lamichhane
 
PPT
ABSTRACT CLASSES AND INTERFACES.ppt
JayanthiM15
 
PPTX
CSharp Presentation
Vishwa Mohan
 
OOP in C++
ppd1961
 
Conditional statements
University of Potsdam
 
TypeScript Introduction
Dmitry Sheiko
 
Complete C++ programming Language Course
Vivek Singh Chandel
 
Iostream in c++
غزالة
 
Polymorphism presentation in java
Ahsan Raja
 
C introduction by thooyavan
Thooyavan Venkatachalam
 
C/C++ language Presentation
S.Saeed H
 
Angular Interview Questions & Answers
Ratnala Charan kumar
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
Function Pointer
Dr-Dipali Meher
 
Object-oriented Programming-with C#
Doncho Minkov
 
C++ Interview Questions
Kaushik Raghupathi
 
Structure in c language
sangrampatil81
 
Functions in c language
Tanmay Modi
 
Unit 7. Functions
Ashim Lamichhane
 
ABSTRACT CLASSES AND INTERFACES.ppt
JayanthiM15
 
CSharp Presentation
Vishwa Mohan
 
Ad

Similar to C++ Programming Course (20)

PPTX
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
PDF
CS225_Prelecture_Notes 2nd
Edward Chen
 
PPTX
Class and object
prabhat kumar
 
PPTX
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
PPTX
Oop objects_classes
sidra tauseef
 
PPTX
class c++
vinay chauhan
 
PPTX
C++ & Data Structure - Unit - first.pptx
KONGUNADU COLLEGE OF ENGINEERING AND TECHNOLOGY
 
PPT
c++ introduction
sai kumar
 
PPT
c++ lecture 1
sai kumar
 
PPT
c++ lecture 1
sai kumar
 
PDF
Introduction to C++ Class & Objects. Book Notes
DSMS Group of Institutes
 
PDF
Chapter 7 C++ As OOP
Amrit Kaur
 
PPTX
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
PPTX
C++.pptx
AbhimanyuKumarYadav3
 
PPTX
ECAP444 - OBJECT ORIENTED PROGRAMMING USING C++.pptx
vmickey4522
 
PPT
static member and static member fumctions.ppt
poojitsaid2021
 
PDF
Introduction to C++
Pranali Chaudhari
 
TXT
Advance C++notes
Rajiv Gupta
 
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
CS225_Prelecture_Notes 2nd
Edward Chen
 
Class and object
prabhat kumar
 
OOPs & C++ UNIT 3
Dr. SURBHI SAROHA
 
Oop objects_classes
sidra tauseef
 
class c++
vinay chauhan
 
C++ & Data Structure - Unit - first.pptx
KONGUNADU COLLEGE OF ENGINEERING AND TECHNOLOGY
 
c++ introduction
sai kumar
 
c++ lecture 1
sai kumar
 
c++ lecture 1
sai kumar
 
Introduction to C++ Class & Objects. Book Notes
DSMS Group of Institutes
 
Chapter 7 C++ As OOP
Amrit Kaur
 
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
ECAP444 - OBJECT ORIENTED PROGRAMMING USING C++.pptx
vmickey4522
 
static member and static member fumctions.ppt
poojitsaid2021
 
Introduction to C++
Pranali Chaudhari
 
Advance C++notes
Rajiv Gupta
 
Ad

Recently uploaded (20)

PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
oapresentation.pptx
mehatdhavalrajubhai
 
Presentation about variables and constant.pptx
kr2589474
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
How to Seamlessly Integrate Salesforce Data Cloud with Marketing Cloud.pdf
NSIQINFOTECH
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Services offered by Dynamic Solutions in Pakistan
DaniyaalAdeemShibli1
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Presentation about variables and constant.pptx
safalsingh810
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 

C++ Programming Course

  • 1. C++ Introductory Course - By Dennis Chang
  • 2. C++ Course Outline OOP Concepts Basic C++ I/O Functions Pointers, addresses and variables Classes and Objects Overloading Templates
  • 3. C++ Course Outline Exception Handling Data Structures Introduction to STL
  • 4. OOP Concept What is OOP? A program implementation style that support the following concepts: – Abstraction – Encapsulation – Inheritance – Polymorphism
  • 5. OOP Concept (Data Abstraction) The ability of packing data together with functions, that allows you to create a new data type.
  • 6. OOP Concept (Inheritance) Inheritance is the process whereby one object acquires characteristics from one or more objects.
  • 7. OOP Concept (Composition) Composition provides the facility for creating a new object from two or more objects.
  • 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. OOP Concept (Polymorphism) Polymorphism refers to the same name taking many forms. See Virtual Functions at a later section.
  • 10. OOP Concepts (Keywords in C++) class delete friend protected handle public inline template new this operator virtual private
  • 11. Basic C++ I/O cin, tied to standard input. cout, tied to standard output.
  • 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. Basic C++ I/O Examples of C++ I/O The output is: Hello World Please enter a number : 5 The number is 5
  • 14. Basic C++ I/O Compare to C built-in library functions: – printf, scanf functions. – Differences between cin/cout and printf/scanf.
  • 15. Functions Declaring functions return_type function_name ( [type][parameter1] , [type][parameter2], ….) Defining functions return_type function_name ([type][parameter1], [type][parameter2], ….) { statements; }
  • 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. 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. 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. Classes and Objects Access Control – Private (Only by own member functions) – Protected (By own and child functions) – Public (By all)
  • 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. 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. 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. 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. 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. Classes and Objects Examples of Member functions implementation: int String::GetLength() const { return m_nLength; }
  • 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. Classes and Objects Derived classes: class subClassName : public baseClassName { //private member declarations public: //public member declarations };
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Pointers, addresses and variables Examples of indirection: int nVariable = 5; int *pPointer = &nVariable; cout << *pPointer << endl; Output : 5
  • 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. 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. 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. 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. 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. 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. Pointers, addresses and variables Memory Allocation/Deallocation – Keywords : • For C : – malloc( ) and free(). • For C++ : – new and delete.
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Overloading Operator Overloading: – Example: class NumberClass { public: //Overloading assignment operator const NumberClass& operator=(const NumberClass &); private: int a; int b; int c; };
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. Exception handling Examples: #include <iostream.h> class Inner { public: Inner(); ~Inner(); void fun(); }; class Outer { public: Outer(); ~Outer(); void fun(); };
  • 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. Exception handling Examples (Con’t): Outer::Outer() { cout << "Outer constructorn"; } Outer::~Outer() { cout << "Outer destructorn"; } void Outer::fun() { Inner in; cout << "Outer funn"; in.fun(); }
  • 74. 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; }
  • 75. Exception handling Examples (Con’t): Generated output:: Outer constructor Inner constructor Outer fun Inner fun Inner destructor Exception 1 occurred Outer destructor
  • 78. Data Structures Queues H K Q…………... FIFO
  • 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. 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. 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. 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. Introduction to STL Allocators – Manages memory allocation for a container. STL Template class : – vector, map, list, stack, deque, set.
  • 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. 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. 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. 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. 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. 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. 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. References C++ How To Program STL Programming from the ground up. http://www.4p8.com/eric.brasseur/cppce n.html MSDN Library