Sie sind auf Seite 1von 30

Object-Oriented Programming using C++ - Day4

Recap of Day 3
• Method Overriding
• Pointer to objects
• Base class pointers pointing to Derived class
• Virtual Functions and Dynamic Binding
• Abstract classes
• Different types of Inheritance

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


2
Technologies Ltd Version no: 1.1
Session plan - Day 4

• Namespaces

• Exception Handling

• Templates
– Generic Functions and Classes

• Introduction to STL

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


3
Technologies Ltd Version no: 1.1
Namespaces

• Motivation

• Consider you purchase two third-party headers namely <vendor1.h> &


<vendor2.h> for different purposes.

• Consider both the header files contain class with the name String but with
different implementation.

• If you include both the headers in an application, there will be two classes with
the same name String. Hence there will be a name clash.

• So Compiler will throw an error. Even if you resolve this error, you will be
ending up with using only one header file.

• So, now How to include both the header files and make use of both the String
classes?

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


4
Technologies Ltd Version no: 1.1
Namespaces – Motivation ( cont.)
// vendor1.h // vendor2.h

... Some code ... ... Some code ...

class String { class String {


... ...
}; };

// My Application
#include "vendor1.h"
#include "vendor2.h“

…Some Code ….

String s1,s2; // Ambiguity

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


5
Technologies Ltd Version no: 1.1
Namespaces – Solution
// vendor1.h // vendor2.h

namespace vendor1 { namespace vendor2 {


... Some code ... ... Some code ...

class String { class String {


... ...
}; };
} }

// My Application
#include "vendor1.h"
#include "vendor2.h“

…Some Code ….

vendor1::String s1,s2; // NO Ambiguity

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


6
Technologies Ltd Version no: 1.1
Namespace
namespace EmployeeNameSpace {
• A namespace is a named class Employee {
area of scope in which all private:
identifiers created by the int m_iEmpId;
programmer are guaranteed float m_fSal,m_HRA;
to be unique . public:
void CalcSal() {
• The identifiers in a //Code to cal Sal
namespace may represent }
variable names, constant };
names, function names, }
structure names, class names
//Object Creation
or other namespaces.
EmployeeNameSpace::Employee oE1;
oE1.CalcSal();
ƒ A namespace can be defined
either at the global level or
//Object Creation – Alternate Method
within another namespace
using namespace EmployeeNameSpace;
(nested namespaces).
Employee oE1;
oE1.CalcSal();
Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
7
Technologies Ltd Version no: 1.1
Nesting of Namespaces
• The namespace cannot be defined as local to a function.
• But the namespaces can be nested.

Nesting of
namespace NS1{ namespace int main(int argc,char**arg)
int iEmpNo; { Correct
namespace NS2{ using namespace NS1;
usage
float fSalary; iEmpNo=1000;
} fSalary=20222.99;
} NS2 :: fSalary=20222.99;
} //End of main

Error : Though the


NS1 is used, the NS2
is to be explicitly used

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


8
Technologies Ltd Version no: 1.1
Unnamed namespace Unnamed External
namespace reference

/* File1.cpp*/ /*File2.cpp*/
namespace { extern int iCount;
int iCount;
} void fnReadCount(){
void fnDisplayCount(){ scanf(“%d”,&iCount);
iCount=99; }
printf(“%d”,iCount);
}

External
reference not
Equivalent to found; ERROR
static in C

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


9
Technologies Ltd Version no: 1.1
The std Namespace
• The standard C++ library defines it’s entire library in it’s own namespace called
std.
• The std namespace has to be included in the beginning of a program as
using namespace std;
• This causes the std namespace to be brought into the current namespace.
• The namespace std contains all the function and the classes defined in any of
these libraries.
• If you don’t declare using namespace std; at the beginning of the program,
then you must use standard objects as given below:
std :: cout<<“hello, this is a sample”;

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


10
Technologies Ltd Version no: 1.1
Exception Handling
• An Exceptional condition is an event that occurs during the execution of C++
program (runtime anomalies) causing a program to interrupt.
Examples: Out-of-bound array subscript, arithmetic overflow or underflow,
division by zero, out of memory, invalid function parameter, etc.,

• An exceptional condition may be either an unexpected error or an excepted


error at an unpredictable time.

• We can broadly classify exceptions into two types


(1) Synchronous exceptions and
(2) Asynchronous exceptions.

• Errors such as division by zero, array-index out of bounds, under flow, etc.,
belong to the synchronous type of exceptions.

• Errors such as keyboard interrupt or any other type of hardware failure belong
to the asynchronous type of exceptions

• C++ proposes many features to effectively deal with synchronous type of


exceptions.
Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
11
Technologies Ltd Version no: 1.1
Exception Handling
• The process of detecting and taking an
appropriate action for exceptions is referred to
try {
exception handling. . . .
• Exception handling involves the following steps.
if(condition) {
(1) Find the error (try), throw exception;
(2) Inform that an error as occurred (throw), }
}
(3) Receive the error information (catch) &
(4) Take corrective actions (Handle) catch(exception) {
//Exception
• The C++ exception handling mechanism is built //Handling
upon three keywords namely try, throw and //Statements
}
catch.

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


12
Technologies Ltd Version no: 1.1
Exception handling - Example
• When the try block throws an # define MAX 5
exception, the program control int main (int argc, char** argv)
leaves the try block and enters the {
catch block. int iArray[MAX],iIndex;
char cConfirm='y';
• In C++, exceptions are nothing but try{
objects/primitives used to transmit do{
information about the problem. if(iArrayIndex>=MAX){
throw 1;
• If the type of the object thrown }else if(iArrayIndex<0){
matches the argument type in the throw -1;
catch statement, then the catch }
block is executed otherwise the }while(iIndex++<=MAX);
program is aborted with the help of }
the abort ( ) function. catch (int iException) {
• If no exception is thrown, the if(iException==1) {
control goes to the statement printf(“Exceeded MAX”);
immediately following the catch }else {
block. printf(“Crossed MIN”);
}}
Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
13
Technologies Ltd Version no: 1.1
Exception handling – Multiple Catch Statements
int main (int argc, char** argv) {
• If multiple catch statements are int iArray[]={‘1’,’2’,’a’,’3’,4’};
found, catch statement of int iIndex=0;
corresponding data type is given try{
the control. do{
if(iIndex>=5){
• If a matching data type is not throw 1;
found, default catch statement is }else
given control. if(isalpha(iArray[iIndex]){
throw ‘e’;
• If a corresponding catch }
statement is not found and no }while(iIndex++<5);
default catch statement is }catch (int iException) {
present, program is terminated by printf(“Exceeded Limit”);
calling abort() function. }catch(char cException) {
printf(“Digits present”);
}catch(. . .) {
printf(“Unhandled Error”);
}
Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
14
Technologies Ltd Version no: 1.1
Exception handling- exception thrown from outside
int main (int argc, char** argv) { void fnValidate(int iArray[],
int iArray[]={‘1’,’2’,’a’,’3’,4’}; int iSize ) {
int iIndex=0; int iIndex=0;
try{ do{
fnValidate(iArray,5); if(iIndex>=5){
}catch (int iException) { throw 1;
printf(“Exceeded Limit”); }else
}catch(char cException) { if(isalpha(iArray[iIndex]){
printf(“Digits present”); throw ‘e’;
}catch(. . .) { }
printf(“Unhandled Error”); }while(iIndex++<5);
} }

• Execution of throw statement will transfer the control to the catch statement of
calling function

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


15
Technologies Ltd Version no: 1.1
Exception handling- throwing an object
ƒ An object of a class type can be thrown from try block.
ƒ This requires a corresponding catch statement.

class MyException {
private: try{
int m_iExpNo; if(codn) {
char m_acExpName[25]; MyExeption oMexp(101,”TSN-Err”);
public: throw oMexp;
MyException(int iD,char acNam[]){ }
m_iExpNo=iD; }
strcpy(m_acExpName,acNam);
} catch(MyException oExeObject){
void DisplayError() { oExecObject.DisplayError();
printout(“%s”,m_acExpName); }
}
};

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


16
Technologies Ltd Version no: 1.1
Templates

• Template is one of C++’s most sophisticated and high-powered feature.


• Templates help you achieve one of the most elusive goals in programming: the
creation of reusable code.
- Hebert Schildt
• Template is a mechanism provided to implement the concept of generic
programming.

• Motivation - Consider the function for swapping two integers.

void fnSwap(int &rA, int &rB) {

int iTemp = rA; Can we use this function for swapping two
floating-point numbers or two objects?
rA = rB;

rB = iTemp; It is possible using Generic Function.


}

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


17
Technologies Ltd Version no: 1.1
Templates
• Allows programmers to create a family of similar classes or functions.

• Eliminate code duplication for different types and thus make the software
development easier and more manageable.
// Function Template int main(int argc,char**argv) {
int iSum;
//Generic data type T, return type T, function float fSum;
//name fnAdd, parameters oT1,oT2 of type T iSum=fnAdd(12,4);
fSum=fnAdd(12.5,3.4);
template <class T>
T fnAdd(T oT1,T oT2) { return 0;
T oTSum; }
oTSum= oT1+oT2;
return oTSum;
}

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


18
Technologies Ltd Version no: 1.1
Function Templates – (Continued..)
//Syntax for a function template

template <class T>


return-type function-name (arguments of type T){

//Body of the function with type T


}
//Syntax for a function template with multiple parameters

template <class T1, class T2>

return-type function-name (arguments of types T1, T2)


{
//Body of the function with types T1, T2, etc.,
}

•Can be overloaded either by template functions or ordinary functions.


•Functions created from function template are called template functions

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


19
Technologies Ltd Version no: 1.1
Class Template
• Concept of template can be extended to classes also

• It is defined similar to an ordinary class except the prefix


template <class T> and the use of generic type T.

• A class created from a template is called as template class.

// Syntax for a class template

template <class T>


class classname
{
//class member specification
//of type T
};

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


20
Technologies Ltd Version no: 1.1
Class Template
• The process of creating a specific class from a template is called class
instantiation.

• The compiler will perform an error analysis only when an instantiation takes
place.

• Hence, it is better to create and debug an ordinary class before converting it


into a template.
// Syntax for a class template with multiple parameters

template <class T1, class T2>


class classname
{
//Body of the class containing members of type T1,T2
};

//syntax for creating objects of class template


class-name <type> object-name(argument list);

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


21
Technologies Ltd Version no: 1.1
Template classes – Stack Example
template <class T> //Creating stack object to store integers
class Stack { Stack <int> oIntStack;
protected: oIntStack.push(10);
T m_aData[5]; oIntStack.push(11);
int m_iTop;
oIntStack.push(12);
public:
printf(“%d”,oIntStack.pop());
Stack() {
printf(“%d”,oIntStack.pop());
m_iTop=-1;
}
void push(T Data) {
if(m_iTop<4) { //Creating stack object to store character
m_aData[++m_iTop]=Data; Stack <char> oCharStack;
} oCharStack.push(‘a’);
} oCharStack.push(‘b’);
T pop(){ oCharStack.push(‘c’);
if(m_iTop>=0) { printf(“%c”,oCharStack.pop());
return (m_aData[m_iTop--])
printf(“%c”,oCharStack.pop());
}
};
Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
22
Technologies Ltd Version no: 1.1
Method Templates

• To define a member function template outside the class, we need to follow


the below given format:

//Syntax for a member function template

template <class T>

return-type class-name <T> :: function-name (argument list)


{
//Body of the function
}

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


23
Technologies Ltd Version no: 1.1
Standard Template Library -STL

• Standard Template Library is a C++ library of container classes, algorithms


and iterators.

• STL is a generic library which provides many algorithms and Data Structures
used in Computer programming.

• Almost every component in STL is a Template

• STL contains many container classes, which contain the other objects.
Examples: vector, list, deque, etc.

• Each of these are template classes and can be instantiated to contain any kind
of objects.

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


24
Technologies Ltd Version no: 1.1
Standard Template Library

• STL provides general-purpose, templatized classes and functions that


implement many popular and commonly used algorithms and data structures.

• For example, support for vectors, lists, queues and stacks.

• In STL there are three foundational items namely containers, algorithms and
iterators.

• Containers
– are objects that hold other objects and there are several different types.
– Sequence container for example vector, list, queues … etc.
– Associative containers which allow efficient retrieval of values based on
keys.
– Each container class defines a set of functions that may be applied to the
container.
– For example, a list container includes functions that insert, delete and
merge elements. A stack includes functions that push and pop values.

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


25
Technologies Ltd Version no: 1.1
Standard Template Library

• Algorithms
– Algorithms act on containers.
– They provide the means by which you will manipulate the contents of
containers including initialization, sorting, searching and transforming the
contents of the containers.

• Iterators
– are objects that act more or less like pointers.
– They give you the ability to cycle through the contents of a container in
much the same way that you would use a pointer to cycle through an array.
– You can increment and decrement iterators.
– The STL also supports reverse iterators. Reverse iterators are either
bidirectional or random-access iterators.

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


26
Technologies Ltd Version no: 1.1
Standard Template Library - Example
// Skeleton Code to demonstrate STL // change contents of list
list
p = objlist.begin();
#include<iostream.h>
#include<list.h> while( p != objlist.end() ) {
int main(int argc, char **argv) { *p = *p + 100;
//create an empty list p++;
list <int> oblist; }
int iIndex;
for(iIndex=0;iIndex<10;iIndex++)
oblist.push_back(i); p = objlist.begin();
cout<<“Size = “<<oblist.size(); cout<<“Contents Modified : “;
cout<<“Contents : “; while( p != objlist.end()) {
list <int>::iterator p = cout<< *p <<“ “ ;
objlist.begin();
while( p != objlist.end()) { p++;
cout<< *p <<“ “ ; }
p++; return 0;
} }

• STL syntax is a bit Complex, but its ease of use is remarkable.


• No C++ Programmer can afford to neglect the STL as it will play an important role

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


27
Technologies Ltd Version no: 1.1
STL - Algorithms

• STL also includes a large collection of useful algorithms that can operate on
containers

• Example: reverse, sort, find, binary_search etc.

• Defined in standard header <algorithm> and <algo.h> for non standard


header.
#include <algorithm>
using namespace std;
int main (int argc, char** argv)
{
int iCount;
int aiArray[10]={1,2,3,4,5,6,7,8,9};
reverse(aiArray,aiArray+9);
for(iCount=0;iCount<10;iCount++){
printf("%d\n",aiArray[iCount]);
}
}
Copyright © 2006, Infosys ER/CORP/CRS/LA38/003
28
Technologies Ltd Version no: 1.1
Summary

• Namespaces

• Exception Handling

• Templates
– Generic Functions and Classes

• Introduction to STL

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


29
Technologies Ltd Version no: 1.1
Thank You!

Copyright © 2006, Infosys ER/CORP/CRS/LA38/003


30
Technologies Ltd Version no: 1.1

Das könnte Ihnen auch gefallen