C++ Abstract Classes and Exception Handling
C++ Abstract Classes and Exception Handling
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
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
Definition Astandard ciass that can be A class that cannot be instantiated directly and
instantiated. contains at least one pure virtuaf function.
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
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
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;
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
odnn ct Coumpilns.
General uses of standard libraries in C++:
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:
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
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
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
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
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
Access Timne Constant time (o(1)`} for random access. Constant time (o(1)) for random
access.
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
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:
CHENNAI CHENNA!
INSTITUTE OF TECHNOLOGY
(AutornonOUs)