0% found this document useful (0 votes)
27 views20 pages

C++ Abstract Classes and Exception Handling

Uploaded by

varunkumaran01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views20 pages

C++ Abstract Classes and Exception Handling

Uploaded by

varunkumaran01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Subject Code/Title:CS4102- C++ PROGRAMMING Unit: IV

UNIT IV
C++ PROGRAMMING ADVANCED FEATURES
Abstract class - Exception handling - Standard libraries - Generic Programming - templates - class
template - function template - STL - containers - iterators function adaptors - allocators
Parameterizing the class.
Abstract class that Cannot be inslantiatd
An abshact class in C+ a class
isecty and is inlnded to Sene as a base cass nay o olur clases. Tt dferes
deived classes and include al lsast ene
une hon, hich is[ a tunetón with no implbmeutalòn in the
Pue virtal pe Vishuad ueton.
abshael class. Deived c lasses ust oversido his
Beclaratón an Abstact elass :
with at lhast ene pue viutual tnetoin.
-dine a chs ws
- a puae viofual nctén is specijiad by using the =0 Splat
in its declavation.
Syntax:
class AbstractClass {
public:
virtual vo id pureVirtualFunction() = 0; // Pure virtual function
// Other member functions and data members

anjets Absthaet clases: Common Code


). shared Behavio Abshaet clases lot gou put
Can
8o that ofher clases deni vol
Bua placa, Ihey make Sura that all
iaauisd tnetions: tings Ces1sant.
clases musl inmplement corlain luetions, kaeping
bijets : hey allow to troat dilfeant types q
s. Koks oib di7enant Coda mOre teible.
in the na loay , making you
ocus on uhat
whal a class
clases et you Cn
44: tides details : Abstack
Shouid do, not hou it does it, hhich halas ús Canizing
Gour Cocla beltn.
eaand: hey make ib Sinples to add hew Ytues
5. Easur to syslom.
chavge hings bikouk aoching te shola
or
CHENNAI CHENNAI
INSTITUTE OF TECHNOLOGY
AvtonomGus)
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV

Code Example:
Example of an abstract class with a pure virtual function:
#include <iostream> I/ Derived class
using namespace std; class Rectangle : public Shape{
|| Abstract base class public:
class Shape { Rectangle(double width, double height):
public: width(width), height(height) {}
II Pure virtual function
virtual void draw() const =0; |/Override pure virtual function
void draw() const override {
1/A regular member function cout << "Drawing a rectangle with width " <<
void setColour(const string& colour) { width <<", height " << height <<" and colour " <<
this->colour = colour; getColour() << endl;
}
string getColour() const {
return colour: private:
double width;
virtual Shape() {}//Virtual destructor for proper double height;
cleanup of derived classes };
protected:
string colour; int main(){
}: / Cannot instantiate an abstract class

I/Derived class
/ Shape shape; // This will cause acompile-time error
class Circle : public Shape{ I/Create instances of derived classes
public: Circle circle(5.0);
Circle(double radius) :radius(radius) [Link]("Red");
[Link]); // Calls Circle's draw method
I/Override pure virtual function
void draw() const override { Rectangle rectangle(4.0, 6.0);
cout << "Drawing a circle with radius " << radius [Link]("Blue");
<<" and colour " << getColour() << endl; [Link]); // Calls Rectangle's draw method
return 0;
private:
double radius; Output:
Drawinga circle with radius 5 and colour Red
Drawing a rectangle with width 4, height 6 and colour Blue

Comparison of a regular class and an abstract class:


Aspect Class Abstract Class

Definition Astandard ciass that can be A class that cannot be instantiated directly and
instantiated. contains at least one pure virtuaf function.

Instantiation Can be instantiated to create objects. Cannot be instantiated directly.

Purpose Used to create objects and define their Used to define a COmmon interface and enforce that
behavior and attributes. derived classes implement specific methods.

Methods Can have concrete methods with Can have pure virtual methods that mnust be
implementations. implenmented by derived classes.

Inheritance Derived classes can inherit and Derived classes must implement all pure virtua!
override methods. methods to be instantiated.

Usage Used for general-purpose object Used to provide a tempiate for derived classes and
creation and functionality. establish a Contract for derived ciasses to follow.

CHENNA CHENNAI
INSTITUTE OF TECHNOLOGY
(AutonomoUs)
Subject Code/Title: CS4102- C++ PROGRAMMING 3 Unit: IV

Differences between Virtual function and Pure Virtual function:


Aspect Virtual Function Pure Virtual Function

Definition Declared with virtual' keyword. Declared with 0 after the function
declaration.

Implementation Can have an implementation in the base class. No implementation in the base clas.

Purpose Allows derived classes to override with their Requires derived classes to provide their
own implementationwhile having a default in own implementation.
the base class.

Base class can be instantiated if it contains Base class cannot be instantiated ifit has
Instantiation
pure virtual functions.
only virtual functions with implementations.
Used to create abstract classes that define a
Usage Used to achieve polymorphism and allow
derived classes to customize behavior. common interface but do not provide
implementation.

Exception handling
buith Uhoxpeetod situalins oy emo5
-allbws prqram to deal ihnw
execution. This is achievod using
thal aiSa
and catch
cduing
clauses.
tipw an .cxapein
Block: T} Contains Code that may
exaptons, excaptanat
d. torpu clause! TE s Is od to sigrablock
transons Conpl to the cateh
Conalition has occagtect. Tt
haown by tbe thp Claus.
a Cateh Bloch : IE handles te eacephön
It detines how he poqram should esjpond to pecfe exeptin[
The try and catch keywords come in pairs:
Syntax:
try {
II Block of code to try
throw exception; I/ Throwan exception when a problem arise
catch () {
/ Block of code to handle errors

Advantages of Exception Handling


handlng: Poides a shueted ay toi us to mag
and esond to ens Consislant ly
sto mainlain
the cot elbaneY and easite hetorCal Stack to hsh
4pe main logie maws to loa pavsd p
3. KoNels thm apprrpiataly
hene lwe Can haudle NNAI CHENNAI
TECHNOLCIGY
INSTITUTE OF TECHNOLOGY
(Atonomous)
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV

4. Unninding of satk: Atomalically cleans yp Tes0urees by coling


doshuclos hown.
hern an excoplon
Allouts us to handle d teraut types
5. Flezibilaly and consitonegiays
spoci<'e a d amsunes Chifoma eor
pogoan
Ct+ StandardExceptions
C+ pides
prgrms. hese ane anamgd
Class hievarchy Exception & Description
Exception Hierarchy
std::exception
std;exception An exception and parent class of all the standard C++ exceptions.
std::bad alloc
This can be thrown by new.
std:bad alloc std:domain_error
std::bad cast
This can be thrown by dynamic cast.
std:bad cast stdinvalid argument std::bad exception
This is useful device to handle unexpected exceptions in a C++
program.
std:bad ypeta std:lengtharror
std::bad typeid
This can be thrown by typeid.
std:bad excoption std:out_of_range std::logic _error
An exception that theoretically can be detected by reading the code.
std:logie foiluro std::domain error
std;overflow_error This is an exception thrown when a mathematically invalid domain
is used.
std:runtino_error std::invalid _argument
std:range orror This is thrown due to invalid arguments.
std::length error
std:underflow_error This is thrown when a too big std::string is created.
std::out of range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset>::operator[|).
std::runtime error
An exception that theoretically cannot be detccted by reading the
code.
std::overflow error
This is thrown if a mathematical overflow occurs.
std::range error
This is occurred when you try to store a value which is out of range.
std::underflow error
This is thrown if a mathematical underflow occurs.
Applications of exception handling:
Calehus amd Teporfs like tele not
und
dasOUTe S, like menmory, i SomehinA
clannupi DrDT Coles, lik
ercapins isaad
disding by 200

CHENNAI
fNSIT
CHENNAI
INSTITUTE OF TECHNOLOGY
(Awtonormous)
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV
EoDs : HandlD5 eDs om ezlenad libTanesliko
dalabe isses
Veor Daput : Validalas aand
5. Das haudlos Wrn9 usUses nput, like
hunnber.
loxt hlhen lapechng
dvalop a Ct+ Ppgam, w h lhe olouing Condi tions :
by Hock Conlains lae ode What, might potontialy ause an
excoplön. Ln his Case, it atlenpls to pofor a diisiön
Openatoin a d nws a sld::n ime ebY RXcepton ib
toe deominator zeD. he catch block atches auy
ceptón ye td:: erceptón (or its daivee clse

Program:
diplay an
messaq
#include <iostream>
#include <stdexcept> / For std::runtimeerror try {
#include <exception>/ Forstd::exception / Attemptto perform the division
int result = divide(numerator, denominator);
using namespace std; cout << "Result: " << result << endl;
}catch (const std::exception& e) {
int divide(int numerator, int denominator) { 1/Catch any std::exception and display the
if (denominator == 0) { error message
throw runtime error("Error: Division by zero cout << "Exception caught:" <<[Link]() <<
is not allowed."): endl;

return numerator/ denominator;


return 0;

int main(0{ Output


int numerator = 10; |Exception caught: Error: Division by zero is not
int denominator=0; allowed.

Standard libraries
sloans - Handles input md Out puit pesations.
I. Tlo
Components ibsheam fos cin, cout, Cam), fshuam (or tile prip
a. Containes - Povdes data shucts o stoing
CollecBtons f oojects . ote.
Consporeuls : Vscto, list Set map, UnOsde ved mep,
3. Algonihs 0fors tenetuns or Common
Sost ,thd, binay- Soavch, Qccumulale,te.
Ceponuts: guctöns
[Link] - Includis Vaoious itty Cowyonouts auddbjets and lande
Componouts : ylelity (oxpaix, tupla),fuletón for enefuán
CHENNAIE CHENNAJ
NSTITUTEF
TECHNQL INSTITUTE (Autonotmous
OF TECHNOLOGY
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV

5. Sing fandling-Moanaqus and Monipatalas Shng


Componaits: &hing', Shingseam, qetln
6. Memony Managneut leols pr nanagng dynamie te noy
Coponeuts? Mnmoylpr Sharad-p,Unquep oak-p)
[Link] Suppot - - Facilitabs mule-hyeading & Concuneuc y
Componauts : toread, ulix, Conditionalvamaole
8. Numies - Supposls mahenmalieal and umine Gporatis

Comporoals! Cmalh (tos mahematieal funehons ) numene-liits


Manags dale and tme Spenatóns
a. Dat avd -time -
Coponuts: choono.
Luprasions - prosdes Sgposk or pallesn mathing
o. Kgular

slandand ibanes in cy+ with name, punposo nd


Comyonats arge expained. hasa included ws mosl

odnn ct Coumpilns.
General uses of standard libraries in C++:

1. Lrput and ouput amd tle irput loutput Gpnations


Inpat
Manago Conscle
. Data &orage
Store; amd manipulae Collec tions f dala wilb
Contatnens like Veelos amd
3. Algorihons
Perfoms Common cpavatons like and
Soonching Dn data.
CHENNA CHENNAI
tNSTIIUT
TECHr Y
INSTITUTE OF TECHNOLOGY
(Autonomor
Unit: IV
Subject Code/Title: CS4102- C++ PROGRAMMING

A. Menony Managmnt -Manle Gypamie meiory Sajely


tools ike smal pointo5 .
vaale ad madily shing sieeadly
s. Shing poxa tions
b. Multtihzaadng- Tpaplal Concunpal,prgrammq
kotlh thcads and 'Synchy piealuon ools
7. Mahematieat Computafons. Exeecnte Complx mnalh
funehons easily
8. pate and Tim- hooy k wib dalas, times aud dain
9. Ey handing - Catc aud manag ems is
shuc tued way.
to Patasn Matcking- Use 0gulay cxpsesions feror ext
Saanching aud "Manipulalion
Generic Programming
paradign that enable & wmtin q code thal is ndep
endeut Speeif'c date vkliaine anaplals, qenie
Proqromng 'allows algnths aid dala shucfuses to wosk woyt uikh
theahy enhaucing Code ousability and lezibilit,
dala tye' Gonudl prgranmtg:
kayCenepts'
I. eplats: TEmplalis
huy alow netons and classos to tpesat with
tyRes. Can ba
Can be classied isto
gunene two 'main ypes :
'Funehóo' templatas- Enabliyg, Csealiny achons alCn tale
.Aas uy dgl s hat Can handle Vajous data ypes.

Bpo
tumplaksAlon
d Functóp lemplals A,guncti amplae opt
Example:
bueprinl toy unet ions
instanttad oth
template <typename T> template <typename T>
T functionName(T parameter) { T max(T a, T b) {
I/ Functionimplementation return (a> b) ?a:b;

3, Class Templates:
Aclass tamplal dtnes a bluepint or cassas. he acuel
Class s Creatid hen the templat is ins tantialidwih scie data
ins tan
Svntax:
template <iypename T>
class ClassName {
I/Class members and methods

CHENNAI CHENNAI
oY INSTITUTE (Awtonomous)
OF TECHNOLOGY
Subject Code/Titlc: CS4102- C++ PROGRAMMING Unit: IV

me T>:DoclarIb
template <typename T>: Aoclaus aa lonplale halo a plorshaldey lepe T
T.
ClassName: ho haine. USed nhan an inslanee
T: Kepseseuls e. dalatpe
Example:
#include <iostream>
using namespace std:
I/Class template int main() {
template typename T> |/Create a Box for int
class Box Box<int> intBox(123);
private: [Link](); // Output: Item: 123
T item:
public: |/Create a Box for string
I|Constructor Box<string> strBox("Hello");
Box(T item) { [Link](); //Output: Item: Hello
this->item = item: return 0:

I/Method to display the item Output


void show() const { Item: 123
cout << "ltem: " << item << endl: Item: Hello

Advantages of GenericProgramming
L. Code Recusabi liy: Use
Examda 4 fehon tb tins he mazium Vale woaks dos
&. Flezibilily: Adapt to auy ye ’ Tenplls honk hith Varas dhta tipes
Exanmple Astack Can
[Link] : Easier lpdatis ’ ix e phe ,ipdali cshore.
Enanpla lenplati tuehön atecls all it 'sas
4 Taypa Sayotychang
Chck tyqps eay
Example- nsue Cenicl Compile time to ami wrfma USsiwis.
tyes
tanune prnqoamming o ctt daveaqes onplalas to lonte typa
code deusabilily anc oxibiy
indapenduut- 'reda, iehy
By wng une lon and'class lonypals, snhancing
chvelopas Can Coe ate yezsal
dle Vanipus dalalyes Making
ad dapblle. Clo hal can hanlle
Code moo' mudular, Mantainable and oicieut.
Templates
=rovide a mechanis) for cdooning fenclirs and classes wtb
hsuiknia
genene tus, alouing lum to opunah lb difpnet dalatyes khal
bots oible and oieieuk by aluing sihgl inpbmadalión to hauda Vastos
Advantages:
LCode Wnl, a sine inplmsutatiin
Asabihty: wnb, ton that wobs with ay type
Coe duhatn.
CHENNAS CHENNAI
tNSTUTE F INSTITUTE OF TECHNOLOGY
(Awtonomous)
Unit: IV
Subject Code/Title: CS4102- C++ PROGRAMMING

2Flexibilty: Mops teuelions vd elases to dalonoud dalatyps bitnul, Changing


'hety Cos0 logBc
[Link]' Cenbalia Code logic in Buu
[Link] gaty iEnsuve that tyo -se lalad eme5 plaa ,ahag
eicatiors:
L. Glenemi Bala Shctses baugtt at Cony ivss.
Use lemplalis to coeate, classes Suckh as dd:: vec tor T> and dd::lster
thal cal, haudle amy dalalype.
[Link] Alqrithnslke sld: ssoot and sld:: find to diorel dala tyes
Any tylalas.
3. Poliey baiad cdesign: Conbine ifnul paieias with lamplalis o roale ahp
and lexible class dsign.
4. Mela Progamnngi
empau- Mme Computatons and opimizkons bmplak
fooy
spcialzaton and SFINAE.
Class template
auy daBa tye.
that can opurate wih
What is a Class Template?
-alloheqthg classes
-bluuprinl oloche d çlas witb one or miore placahalden pes,
hlan oe eoeat an ins tonce Y cas
are replaced
Same ewih
lassacHa data
Can handle daalpes wlieut Code duplicaton
How Does It Enable Generic Programming? us to wnte
class lcnplal geurie pngsemning by, loingTh's eliunatas
cass defynitön' hal n hok wto mullpla
a
Singfe
the puoel os, uliplo cleys nihoins loo diloit dalaypes and promohs
Cole ofrzubabilly
Syntax qd
a Class Template ylexbuli
template <typename T> template <typename T>: Declares a template with a placeholder type T.
class ClassName { ClassName: The name of the class.
I| Class members and methods}; T: Represents the data type that will be used when an instan ce of the
class is created.
Advantages of using class templates in, works ws
1. Code Reusability-one a Sinyle closs
2. Type Safety- nsure
thalt
[Link] cthess al Cmpile tim.
dalalype
3. Flexibility-Easly eyel qoune plasys thal can hadle difeent datale.
4. MaintainabilityReclcecsda dplicatin, making the eode. easiey to
aintain.
s. Performance - Aehieva batex purqomante witb ypt-Speitie Gpini2töns dunC.
Ccmpilhon
Example of aClass Template
include <iostream> public:
#include <stdexcept> 1/ Constructor to initialize the stack
using namespace std; Stack(int size) {
I/ Stack template class capacity = size;
template <typename T> arr = new T[capacity];
class Stack { top =-1;
private:
T* arr: /Destructor to clean up allocated memory
int top; -Stack) {
int capacity; delete[] arr;
CHENNAI CHENNAI
TECHNOLC)GY INSTITUTE (AutonornQus)
OF TECHNOLOGY
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV

/ Method to push an element onto the stack


[Link](20);
cout << "Integer Stack Size: " << [Link]()
void push(T value) { << endl;
if (top == capacity - 1) { cout << "Popped from Integer Stack:
throw overflow error("Stack overflow"); [Link]() << endI;
Cout << "Is
Integer Stack Empty?
arr[++ttop]= value; ([Link]) ? "Yes" : "No") << endl;
/ Methodto pop anclement from the stack |/ Create a stack for doubles
T pop) { Stack<double> doubleStack(5);
if (top == -l) { [Link](3.14);
throw underflow error("Stack
underflow"): [Link](2.71);
cout << "Double Stack Size:
[Link]() << endl;
return arr[top--]: cout << "Popped from Double Stack: " <<
||Method to check if the stack is empty [Link]() <<endl;
cout <K "Is Double Stack Empty? <<
bool empty() const {
return top ==-1; ([Link]() ? "Yes": "No") << endi;
return 0;
1/ Method to get the size of the stack
int size() const { Output:
Integer Stack Size: 2
return top + 1;
Popped from Integer Stack: 20
}}: IsInteger Stack Empty? No
int main() { Double Stack Size: 2
||Create a stack for integers Popped from Double Stack: 2.71
Stack<int> intStack(10); Is Double Stack Empty? No
[Link](10);
Explanation:
Class Definition:
Constructor: Inittali2e5 ha stack and Bots it si.
Destructor: Freos the alloeted menory
Push Method: Ads an ibm to te slack,thping
Pop Method:Remoyes and ehns the lop ita teun
Empty Method: Chucks i7 the stac k B enapty
Size Method: Retuons he numbes
Main Function:
tlonns in the slack.
Integer Stack: C3eatas a sack tox adds and pefoyms
cprratins to chaek Sie , Pop an i
Double Stack: C3ees a slack exdoublosactds twodoudes aud penleaa sini lay
Function template
Detinition: ABepninl ter Caeating nctións that Can Opvale hwitb dleul
dalalgpes. Tl alluws ws o di<ra tunehirs logte
4Spieq'e daabypes, Making ta yune tin that
heets the tenekin's
Support for Generic Programming: Functin tamplalis Suppob qeie prqramming
by allowing us to ona Single funehön inihoo that woko wt
a

CHENNAI
INSTITUTE OF TECHNOLOGY
(Autnenou)
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV
amy dalalpa. his Bane
avoids Code.
Can be instanliated
wilh voriDNS
Syntax:
template <typename T>
ReturnType functionName(T parameter)
/Function implementation

| e ,tonplalithat<lypaname T> poeilies lal T i a plaahstds tos


a dalatyod uttb oh bo do fined ihen thu func ton i usecd. Tbo' T
he actuai dalaly hemng cunilati.
Advantages'of using function templates in C++:
1. Code Reusa bility. lovnu cue. feinchon lhal luoshs wh
2. Type Safety nsuve
dala type
Ceseel types ao Usod wrbesCaught dl conale ti
3. Flexibility-Cseal
Reduced qurene tneohs hee co, haudle cdiorat datd lypes sdsly
Code Dupliation -AvoO
5. Consistency- Maintain a Consistontntna
Example: haudla
Same
devenl ic.
nton
Define asimple function template that finds the maximum of two values.
Code Example:
#include <iostream>
using namespace std;
/Function template for finding the maximum oftwo values
template <typename T>
Tmax(T a, Tb) {
return (a >b) ?[Link]

int main) {
I/Using the max function template with integers
int intl = 10, int2 =20:
cout <<Max of" << intl <<" and " << int2 <<" is " << max(int 1, int2) << endl;
/ Using the max function template with doubles
double doublel = 3.14, double2 =2.71;
cout << "Max of" << doublel <<" and " << double2 << " is " << max(doublel, double2) << endi;
1/Using the max function template with strings
string strl ="Apple", str2 = "Banana";
cout << "Max of" << strl << "and " << str2 <<" is "<< max(strl, str2) <<< endl:

return 0;

Output:
Max of 10 and 20 is 20
Max of 3.14 and 2.71 is 3.14

Explanation:
1. Function Template Definition:
<typenamu Ts line speafus thal Tba pauhalder for
he tenmplale
auy data, type max Compaes tup Values o type T and setuns taa
* The tnefüb
g0ealay of e two. CHENNAI
TUTE oF CHENNA!
TECNOOGY INSTITUTE(Autononous)
OF TECHNOLOGy
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV

2. Instantiation with Different Types:


Integers: mazlinti, int 2) b called with intger argumas. Conpiay
Cveates a Vensin d the mare func hon
Doubles: hyax (doblal, double 2) Shectcaly
A Sepasate Vypsuôn d be max uneto n
Strings: max (sb), sBa) s, callad wrth Shing Anothey
Benefit_:
Reusability:he wnle the max tunchon enca, and it cn hadle diferout lp
Flexibility:ha Sam unchôn Bosks witb diesut dalalpes witiout Mdifteaton.
Code Reduction; Elininal s Be nad to wnte mullile vasions f Sailasfetör
tos degeveut typas.
Function lnplalas io Ctt that enhamas code ozibi
and euse, Supporlong the psinciplus geneie
Differentiate class template and function template with suitable examples. ponqramming
Description Class Template Function Template
Definition Defines a blueprint for a class that can operate Defines a blueprint for a function that can operate
with different data types. with different data types.
Syntax template <typename T> class template <typename T> ReturnType
ClassName {... }; FunctionName(Parameters) {.. }
Use Case Used to create classes that handle multiple Used to create functions that handle multiple
types. types.
Instantiation Instantiated by specifying the type when Instantiated by specifying the type when calling the
creating an object. function.

Example Code #include <iostream> #include <iostream>


using namespace std; using namespace std;
/ Class template |/Function template
template <typename T> template <typename T>
class Box { void swap(T& a, T& b) {
private: T temp = a;
T item; a =b;
public: b=temp;
/ Normal constructor format
Box(T item) { int main() {
this->item = item; } int x = 10, y = 20;
void show) const { swap(x, y); / Swap integers
cout <K "Item:" << item << end: cout << "x:"<<X . y:" <<y<< endl;
}}; I/Output: x: 20, y: 10
int main(0 { double a= 1.1, b= 2.2;
Box<int> intBox(123); /Box for int swap(a, b); // Swap doubles
Box<string> strBox("Hello"); // Box for string cout << "a: " <<a <<", b: " <<b<< endl:
[Link](); // Output: Item: 123 I/Output: a: 2.2, b: 1.1
[Link](); // Output: Item: Hello return 0;
return 0;}
Output: Output:
Item: 123 x: 20, y: 10
Item: Hello a: 2.2, b: 1.1
Usage Managing collections of items with different Performing operations on data of any type, such as
Example types, such as a Box class for various data types. swapping two values.

CHENNAI
TECHNOLCGY INSTITUTE(Avtosomous)
OFTECHNOLOGY
Subject Code/Title: CS4102- C++ PROGRAMMING Unit: IV

STL
The Ct slandavd Iibsay pnvidos a widedoelupal ramge af data
shuctuas amd algorilhms thal saenline by Toducin
tplomoulations.
te nead for Cusone are centainess , algonthns,
d
Componats [Link] STL
he pranclön Sandard khsany coding
simplilirstask:
eNamplos shoo how te
1. Containers
Conains are hold and manage Cellaetins
dala shchures that
Contain clses)
Chjcls. h stamdar Lbsary os Seveal pe-ingpla mutecf
éach Suited to diferoul heeds: Se. Bovdos ast andom accs
in
anay thal Can qrwoequeay nacd to access elamnls byüo
std::veetor: Adynanesbysing"eleeds uben tyou
and is idal os COut << num <<'" :
Example:
#include <iostream>
#include <vector> cout << endl:
using namespace std; return 0;
int main) {
vector<int> vec = {1, 2, 3, 4, 5}; Output:
vec.push_back(6); l/Adding an element 123456
for (int num : vec) {
aseiattve canlainey that slores key value pairs, boviades ast
std::map: 4 Soobd
lookup, insetion and deleton based on
Example:
#include <iostream> cout << [Link] << " is "<< [Link] <<
#include <map> "years old." << endl:
using namespace std; }
return 0:
int main() {
map<string, int> ageMap;
ageMap["Alice"] = 30; Output
Alice is 30 years old.
ageMap["Bob"] = 25;
for (const auto& pair ; Bob is 25 years old.
td::list: A doublu i ist thal alowsekcint Lnsosftons and dale töns
pom anyhese in be lzt bul do25 nol supposl Yandons accass.
Éxample:
#include <iostream> COut K< numn <«" ":
#include <list>
using namespace std; cout << end1:
int main0 { return 0;
list<int> myList = {1, 2, 3, 4};
[Link] front(0); //Add element to the Output
front 0 123 4
for (int num : myList) {
2. Algerithmsonand ibray includes a Vaialy q algorithms hal operde
corta inas. These Jecduo
saduc lhe necd fov Custons inplmenkatons
Comon opevafins algohms
On
o ke Soyftng amd Sasehing.
Std::sort: Description: Sorts elements in a container.
CHENNAIE
CHENNAI
INSTITUTE (AwononGUs)
OF TECHNOLOGY
Subject Code/Title: CS4102- C++ PROGRAMMING 15 Unit: IV

Iterators
Tlesalos in o sandand lemplalo Libraoy (sTL) ne a Cneial
Conporut , o tacl latihg goneie pgaming uy poovele
and abstract uy
a

to, 43aviyse amd manipulat elmants s


Containes, egarl~ss o tho. Conlalhes's shuchune.
Roles of Iterators:
1.
J
Abstraction and Uniformity
Povdo a Consistonl hay o acess elomeuts acDss
Lndidying
tepes, hahing Cale more genene nd eusabl.
diforenl Conla
2. Decoupling Algórithms from Contaíners
Allow lorhs to wok Contain1 hat supo sts lesalos
enhancing t 4
3. Flexibility Atross
and codo
Suppost Vanous Containes wb a Common
Advantages of Iterators Over Traditional Indexing
Container Independence
Containey hot just hose orb Tandorm access
Consistency
y Poode a
Flexibility
lemuls,Smpyyngto taverse
> Allcuo custonm trarersal like moung toward backwad
Safety
Rucluce the visk o eut-fbounds
Performnance Containes automatcally -
by badlng
for Spacilie Conlaines
The program given below demonstrates iterating over a vector and a list and printing the ir elements.

#include <iostream> 1/Example with std::list


#include <vector list<int> Ist = {10, 20, 30, 40, 50};
#include <list> cout << "List elements using iterators:" <<
using namespace std; endl;
int main) { I/ Using iterator to traverse the list
/ Example with std::vector for (list<int>::iterator it = [Link](); it !=
vector<char> vec = {'A,"B', 'C, 'D, 'E}; [Link](); +tit) {
cout << "Vector elements using iterators:" << COut <K *it <<" !.
endl;
/ Using iterator to traverse the vector cout << endl:
for (vector<char>::iteratorit = [Link]); it != return 0; Output:
Vector elements using iterators:
[Link](); ++it) { ABCDE
Cout <K *it <<" ". List elements using iterators:
10 20 30 40 50
cout << endl:

CHENNAI CHENNAI
INSTITUTE OF TECHNOLOGY
(Avt onomaUs)
Subject Code/Title: C$4102- C++ PROGRAMMING /8 16 Unit: IV

Function adaptors
4Jaue cl4sses in lhe Standoad engda Libas(sTL) Such as
sld:: sack ad std:i que Poude a specialised intalace t
data is pecilie tho behans
existng (onlainex tyos ka sta::Ve clor, sld::doge,or std::ls
to align with paheula chachures, Buch as slacks nd qeus.
TkPy Coslain tatis by enforeing spocilie accass palens ond Opoatid
he std::slack adapls implimuuls
last-in, ost out (LIFO) data
Shuctne
bhe to bo .% ho, mosl
chuckure
that
ece nelly acdod elemeut
oulu th yst
stack, ensunng hat eleens ao added ano allows lhe tep elemeut t
to
Key opcrations inude: zemovecl em Ohe end
push(): Adds an element to the top.
pop): Removes the top element.
top(): Accesses the top element. Output
For example, consider the following code: Top element: 3
Top element after pop: 2
#include <iostream>
#include <stack> [Link](3);
cout << "Top element: " << stack [Link]()
#include <vector> << endi;
using namespace std; [Link]();
int main(0 { COut << "Top element after pop: <<
stack<int,vector<int>> stackVector: [Link]) << endl;
/ Using std::vector as the underlying container return 0;
[Link](1);
[Link](2);
In this cdo, loe use std::Vecto as the. ndeolyng, Containas
std::stack. This, means lhat sld:: Slacls adapts le std:: vecoy to
bahavo ike a claels, ey LIFO eprratons ,"he std:: vec to
Ppvicle the pelu
s
dala acco ing to he apoislack
eshicts accass to he
LIFD
std::queue pincapla
The tart qusua adoplan epusouts a fat-in. ist out (FIFO) Aala Sacla
hheop thu ist .element adked s he isst oue to be 0 moved. This Shuctac
allows elements to be added at he bak nd semoved pom he onl.I
Supootspush):
¢pratons Such as :
Adds an elnit to be baek.
pop): Re moves tho ronl eleeul.
front():Aceses te onl elemt.
back(): Accesses lhe Aast elemul.
Consider the following code:
#include <iostrcam> [Link](2):
#include <queue> [Link](3);
#include <list> cout << "Front element: " << queueList. front()
using namespace std; << endl;
int main() { [Link]();
queue<int, list<int>> queuelList; cout << "Front element after pop: <<

I/ Using std::list as the underlying container queueList. front() <<< endl; Ouput.
Front element: 1
queuel,[Link](1); return0:} Front element aMer pop 2

CHENNAIS CHENNA
INSTITUTE(Autonoos)
OFTECHNOLOGY
Subject Code/Title: CS4102- C++ PROGRAMMING 17
Unit: I
Jn the above coole, e, 5e Sld:: lisl as the Lnolyig couilangs
fos std::q uoe-lo4, Std:qe ue. adapts lbe sld:. lst to bohae ike
quse,'enabling FIFO bpatons. Theld:: l Prdas Ce slonye ,
added al
enabi"no
he ed
Relationship to Underlying Container Types
Thse adaples ly On a n
paltem, hhene elements "ae

Lndealyinq Conatner to store the


elenens, but hey reshiet hoo we intinat Loib lhe dala b it the
inlsdec Usecase,(IFo, Jor stdi: slack, EiF Ofor stdi:g)
By dafaul, bolh std::slack aud ad::quuue use sld:idsua
dillerut Container
Qs theiy cundeylying Containgy bul we ean qeety a
Wen ergatng hn, as shown is he erampls above .Tho choice f the
Chaleslying c&ntains Can aJel pondomane charactnshes but cdes not
the fundaveata! kuhaiov
clhage he adaplor.
DiffereHces between std::vector and std::deque in terms of perforhnance and use c£ses:
Aspect std::vector std::deque

Memory Layout Contiguous memory block. Disjoint memory blocks.

Access Timne Constant time (o(1)`} for random access. Constant time (o(1)) for random
access.

Insertion/Deletion at End Amortized constant time (o(1)). Constant time(o(1)*).


Insertion/Deletion at Linear time (o(n)}; inefficient. Constant time (o(1)): efficient.
Front

Insertion/Deletion in Linear time (o(n)). Linear time (o(n)).


Middle

Realiocation Reallocation involves copyingal No reallocation for insertions at

elements; expensive when growing. either end; efficient memory use.

Iteration Fast due to contiguous memory. Slightiy slower due to non


contiguous memory blocks.

Use Case Best for dynamic arrays where frequent Best for scenarios requiring frequent
random access and appending are insertions/deletions at bothends.
needed.

Memory Overhead Lower, due to contiquOus allocation. Higher, due to managing multiple
memory blocks.

Stability During Less stable during insertions/deletions, More stable, especially when
especially when reallocation occurs. operating at the ends.
insertions/Deletions

Allocator Lenplale ibsasy (sT) ane a teudamitaf


)IDCaovs in lhe slandard
naqemel pDide a savdasdizcd
nentry alocahön and dallocahón foy Conlainess
STL.
Role of Allocators
1. Memory Management Abstraction: ealloeatinpo
Alloealös abshact the popCess mmony alocaton md shyetures.
a Unitom, intyacealtiwe
oy maag acns diResoul dala,
his abshaefon STe ho kori Be avd adaplable to
aleront MeMory Manaqomenl Statogies. CHENNAI CHENNAI
INSTITUTE OF TECHNOLOGY
TECHNOL (Auionomous)
Subject Code/Title: CS4102- C++ PROGRAMMING 18 Unit: Iy
2. Custom Memory Management:
velops Can tneh Cun allbeeatos to wse Ceslom memoy manapmt
Suckh asa
tacking'ogeltng
technitws,Such
poolng
pea kmsing po lonmance cor irtaialn uilh gpecilte
[Link] Syslints.
Lsing allocalos ensuses in how hanllod aenss
Vanous STL Const'stney.
Centainers ,Such
4. Efficiency:
momory
as Vstd:: Vacto, stdi: ist and ddi:map.
Alealos can impre etfeieney by, Deasing tragala
and minimi 2ing
Allocator Interface
fraqueut allaatns mandl.° e
All atator s STL typically prides le ttoing opuxatons :
allbale (si2a -t n): Allbcals Menory o n chyucts.
deallocate (TP, Siat):ellocalas nmamovy pavoysly dcaid rnobia
Constuet (T4 P Const Tx value): Consets an coject ß type T
al he locaton pointad to
Default Allocator
an
hIhe
h i l tallocator lsed'by STL Containes s Std:iallocalor
the gobal and
Example of Using a Custom Allocator
Below is a simple example demonstrating the use of a custom allocator with std::vector:
#include <iostream> <<"elements." << endl;
#include <vector> allocator<T>::deallocate(p, n);
#include <memory> / For std::allocator
using namespace std; int main){
1/Custom allocator example 1/Create a vector using the custom allocator
template <typename T> vector<int, CustomAllocator<int>> myVector:
class CustomAllocator : public allocator<T>{ || Addsome elements
public: [Link] back(1 );
using allocator<T>::allocator; // Inherit constructors [Link] back(2);
I/Overload allocate and deallocate methods [Link] back(3);
T* allocate(size tn){ I/ Print elements
cout << "CustomAllocator: Allocating " <<n<< cout <<"Vector elements: ";
elements." << endl; for (const auto& elem : myVector)
return allocator<T>::allocate(n); cout <K elem <<"".
cout << endl:
void deallocate(T* p, size t n) { return 0:
Output:
cout << "CustomAllocator: Deallocating " <<n } CustomAllocator: Allocating lelements.
CustomAllocator: Allocating Ielements.
CustomAllocator: Allocating I elements.
Vector elements:123
Explanation of Example: CustomAllocator: Dcallocating 3 elements.
1. Custom Allocator Definition: and owrotes allocate
+, CustonAllocaloy inhnts fom sladii allocalor in hiy case)
ana dealocate nnethds to iñclude Custon belato a laghg
2. Usagein std::vector:
CHENNAI CHECNAI
Y INSTITUTE OF TECHNOLOGY
(Autosomous)
Subject Code/Title: CS4102- C++ PROGRAMMING 19 Unit: IV

* hhen elaments ae added oy 3emoved, lbe cLstom alloeetos 'e


ollocata and cleallocnte me hods ane e alled.
Albcato% ase a omponeul sre bat monage menory
allocaton and dealloa ton os Containus.
Thuy porvide a Consislent and exible way to havde nemoy.
allening
The
cuslos yeniory anagenunt Shalogias
shátagies
fault allbcaloy tsls stankad new auld deli le,bul
Custonm allceatos Can bo dofined to tailos memony Manaqenuuk reds.
Parameterizing the class

laancasiing a class in CH de<os to the prachce ot o


designing classos° in a tlerible aud eeable bay by lowing
then toopenale wilh slilleaout ypes 03 Valuos.
This s typically achived vsing :
Templates:kine classes at nhandle any typa Specfiad at inslaton
2. Parameterized Constructors: Use
d clas instance s parametos
to SoEhitiog' valuss
3. Template Parameters: customize classes furtbes Using hoh-ye paarains
Buch as Urtages o pointins.
Advantages:
1. Type Safety: Ensuves the class woks wih Spuciftc tyres, catching emOs at Comple ime.
2.3. Flexible
ReusableSizes:Lots
Code; Albwsyo you tb use he sane class wlb pronl dalat-pdeing cde apli ficns
sot Siz0s 0r limits(eg- asay Ses hhan you Caali an inslaheo hicas.
4. Easier Maintenancechanges axe mad in one olace smakirg updalis
and less e pipne. simpler
5. Improved Performance: hensaas ptimizoc Cede for specifre tepes, enhancingl
exeutn etieiney.
Performing ParameteYízing a cláss in C++:
class tonplabsConstnctors
yBy Using Pasametorhed
ParamateNs
3) By Usin Lmpla
1. Class Templates
tenplale allows to dofine a class orth
Dslinits n: AClas ean than Croal insanees this cbss lorts
genenie tyis. You
Gpeeifie typs.
Progratn:
#include <iostream> MyClass<int> intObject(10); //T is int
using namespace std; MyClass<double> doubleObject(5.5); // Tis double
template<typename T> cout << "intObject data: " << [Link] Data() << endl;
class MyClass cout << "doubleObject data: " << [Link] Data()
T data; <<endl:
return 0:
public:
MyClass(T val)
data = val; } rOutput:
T getData() const { intObject data: 10
return data; }}; doubleObject data: 5.5
int main() |
CHENNAI
TECHNOLCOGY OF TETECHNOLCOGY
INSTITUTE (Avtononous)
Subject Code/Title: CS4102- C++ PROGRAMMING 20
Unit: IV
2. Parameterizcd Constructors

Panapulevize class bohavoy Lsing Constueto parvamles to ini ial e


Definition:
Cbjeets wib difo2nt Values. hcight <<cndi;
Prógram:
#include <iostream>
using namespacc std;
class Box { int main) {
int width: Box boxl(10, 20); // Crcates a Box with width
int height: 10 and hcight 20
public:
Box(int w, int h) { [Link]():
width = W;
height = h; return 0:

voiddisplay() const { Output:


cout << "Width: " << width <<", Height: " << Width: 10, Height: 20

3. Template Parameters
Definition:
Class tomplatig Can also LE2 non-typo, parameos , like tntgrs
poinlrs , to' fuhes Customize the clas bohavio%.
Program:
#include <iostream> int get(int index) const {
using namespace std; return (index <Size) ? arr[index]: -1;
template<<int Size>
class FixedSizeArray {
int arr(Size]; int main) {
public: FixedSize Array<5> myArray; I/Creates an array
voidset(int index, int value) with fixed size 5
if (index <Size) { Standard
arr[index]= value; [Link](0, 10);
[Link](1, 20); << endl:

cout << "Element at index 0: " << [Link](0) return 0;


<< endl;
cout << "Element at index 1:" <<myArray. get(1 )
Output:
Element at index 0: 10
Element at index 1: 20

ClassTemplates: Allovo you to eoeate classes that havdle Sctl'e


devent dalalyns
Parameterized Constructors: initali2e Classnembes witth
Template Parameters: PrnaHou, ole Customizatlon wth ronyje panamals

CHENNAI CHENNA!
INSTITUTE OF TECHNOLOGY
(AutornonOUs)

You might also like