Lecture Notes: Unit Iii - C++ Programming Advanced Features
Lecture Notes: Unit Iii - C++ Programming Advanced Features
asia
Lecture Notes
Abstract class.
o Class that contains at least one pure virtual function is known as abstract class.
o Abstract classes cannot be instantiated, but can be subclassed.
o Classes that are derived from abstract classes must implement pure virtual functions of the
abstract class. The derived class are also known as concrete classes.
#include <iostream.h>
class shape // Abstract class
{
public:
virtual void display() = 0;
};
class triangle : public shape // Concrete class
{
public:
void display()
{
cout << "Triangle shape";
}
};
class rectangle : public shape // Concrete class
{
public:
void display()
{
cout << "Rectangle shape";
}
};
int main()
{
triangle t1;
t1.display();
rectangle r1;
r1.display();
return 0;
}
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
Exception
o Exceptions are runtime anomalies that a program may encounter while executing.
o Synchronous exceptions out-of-range index, divide by zero, etc., could be handled
o Asynchronous exceptions such as keyboard interrupt are beyond user control.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
standard libraries.
o C++ libraries are broadly classified into two types.
o Standard Function Library consisting of general-purpose, stand-alone functions inherited
from
C. Some of them are:
o String and character handling
o Mathematical
o Date and time
o Dynamic allocation
o Object Oriented Class Library which is a collection of classes and associated functions.
Some
of them are:
o Standard C++ I/O Classes
o String Class
o STL Container Classes, Algorithms, Function Objects, Iterators, Allocators
o Exception Handling Classes
String Class
o Standard C++ provides a new class called stringby including <string> header file.
# include <string>
using namespace std;
o The stringclass takes care of memory management, allows use of overloaded operators
and provides a set of member functions
o A string object can be defined by using default/parameterized/copy constructor
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
List the functions applicable to the string class. Explain with an example.
append() appends full/part of a string
empty() returns true if the string is empty
erase() removes no. of characters specified from the given position
find() searches for the occurrence of a substring
insert() inserts no. of characters specified at the given position
length() returns length of the string
replace() replaces characters of a string with another string/substring
swap() swaps the string contents with the invoked string
substr() returns a substring of the given string
find_first_of()returns the position of first occurrence of the given character
find_last_of() returns the position of last occurrence of the given character
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("ANSI "),s2("Standard "),s3,s4;
cin >> s3; // C++
s4 = s3;
if (s3 == s4)
cout << "Strings s3 and s4 are identical";
s4 = s1 + s2 + s3;
cout << s4; // ANSI Standard C++
string s5 = "ISO ";
cout << s2.insert(0,s5); // ISO Standard
cout << s2.append(s3); // ISO Standard C++ cout <<
s4.erase(7,3); // ANSI Stard C++ cout << s2.replace(0,4,s1);
// ANSI Standard C++ s1.swap(s3);
cout << s1 << s3; // s1: C++ s3: ANSI
cout << s2.substr(7,3); // and cout <<
s2.find_first_of('a'); // 7 for(int i=0; i<s2.length();
i++)
cout << s2[i];
return 0;
}
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
generic programming
o Generic programming enables to define generic classes and functions. It is implemented
in C++
using
templates
.
o Compiler uses the template to generate different instances through template parameters.
o It improves programming efficiency and allows the programmer to defer more of the
work to the compiler.
function template
o A generic function defines a set of operations that can be applied to various types of data.
o The type of data that the function will operate upon is passed as a parameter.
o Function template avoids code redundancy among structurally similar families of
functions.
o Compiler uses function template to generate version of the function that is needed.
o A function that is an instance of a template is also called a template function.
template <class T>
returntype functionname(arguments)
{
}
o The templatekeyword indicates that a function template is defined.
o The keyword class means generic type and parameter T is known as template
argument, which can be substituted by any type.
#include <iostream.h>
template <class T> // Template function void arrange(T arr[],
int size)
{
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if (arr[i] > arr[j])
{
T temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
int main()
{
int x[6] = {1,-4,8,0,3,5};
float y[6] = {2.2,-0.4,3.5,1.9,2.7,0.7};
char z[7] = {'I' 'n','d','i','a','n'};
arrange(x,
6);
arrange(y,
6);
arrange(z,
6);
cout << "Sorted Arrays \n Int \t Float \t Char \n";
for (int i=0; i<6; i++)
cout << x[i] << "\t" << y[i] << "\t" << z[i] << "\n";
retur
n 0;
}
o For each call, the compiler generates the complete function, replacing the type
parameter with the argument type (int/float/char).
Class Template
o Like generic functions, generic classes can be created.
o A generic class that defines algorithms used by that class and the actual type of the data
being manipulated will be specified as a parameter when objects of that class are created.
o Class templates are used for data storage (container) classes. Class templates are also
called parameterized types.
template <classT>
class
{
member of type T
};
o Classes are instantiated by defining an object using the template argument. A class
created from a class template is called template class.
classname <type>objectname;
o Member functions of a class template are defined externally as function templates.
template <classT>
returntype classname <T>::functionname (arguments)
{
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
#include <iostream.h>
const int size = 5;
template <class T>
class mystack
{
T st[size];
int top;
public:
mystack()
{
top = -1;
}
void push(T var)
{
st[++top] = var;
}
T pop()
{
return st[top--];
}
bool empty()
{
if (top < 0)
return true;
else
return false;
}
bool full()
{
if (top == size-1)
return true;
else
return false;
}
};
int main()
{
mystack <char> s1; // Character Stack
mystack <int> s2; // Integer stack
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
while (!s1.empty())
cout << s1.pop();
return 0;
}
File Handling
o A file is a collection of related data stored on an auxiliary storage device.
o In file I/O, input refers to reading from a file and output is writing contents to a file.
o <fstream.h>must be included for file I/O.
C++ provides the following classes for high-level file handling.
ios
istream ostream
iostream
ifstream ofstream
fstream
fstreambase
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
Detect End-Of-File
o When a file is read continuously, eventually an end-of-file (EOF) condition
will be encountered.
o The EOF is a signal sent to indicate that there is no more data to read.
o Detecting EOF is necessary to prevent any further reading using a loop.
o The fileobject returns 0when end-of-file is reached causing the loop to terminate.
while(fsobj)
{
closing files
o When a program terminates, the fileobjects goes out of scope.
o This calls the destructor that closes the file.
o However, it is recommended to close the files using close()method.
fsobj.close();
o A closed fileobject can be opened in another mode.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
#include <iostream.h>
#include <fstream.h>
int main()
{
ofstream fp; char ch;
fp.open("sample.txt");
cout << "Ctrl + Z to terminate: ";
while( (ch = cin.get()) != EOF)
fp.put(ch);
fp.close();
return 0;
}
o The following program reads the file character-by-character and determines number of
vowel present.
#include <iostream.h>
#include <fstream.h>
#include <ctype.h>
int main()
{
ifstream fp;
char ch;
int vc = 0;
fp.open("sample.txt");
while(fp)
{
ch = fp.get();
switch(tolower(ch))
{
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
case 'a' : case 'e' : case 'i' : case 'o' : case 'u' :
}
}
vc++;
break;
cout << " No. of vowels : " << vc;
fp.close();
return 0;
}
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
file pointer
o Each file object has two associated file pointers namely get (input) and put (output) pointer.
o For each file I/O, the appropriate pointer is automatically advanced.
o The default action for pointers on opening a file are:
o ios::inʊget pointer is moved to beginning of the file
o ios::outʊput pointer is moved to beginning of the file
o ios::appʊput pointer is moved to end of the file
o File pointers can be moved randomly using functions seekg()and seekp().
Function Description
seekg(abspos) o Moves the get pointer to the specified byte.
o The positional value may be absolute or relative.
seekg(offset,refpos)
o If relative, refpos is a constant ios::beg, ios::cur, or ios::end
referring to start, current, and end of the file.
fobj.seekg(10,ios::cur);
seekp(abspos) o Like seekg, seekp( ) moves put pointer.
seekp(offset,refpos) fobj.seekg(100);
tellg() o Returns current position of the get pointer.
tellp() o Returns current position of the put pointer.
#include <fstream.h>
#include <iostream.h>
class student
{
int rollno; char name[20];
int arrear; float cgpa;
public:
void getdata()
{
cin >> rollno >> name >> arrear >> cgpa;
}
void display()
{
cout << rollno << name << arrear << cgpa;
}
};
int main()
{
fstream fobj; student s1; int
ch, rno;
cout << "1.Append 2.Display"; cout << "Enter
CS6301 Programming & Data Structures -II Page 13
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
STL
Component Description
Container object that is able to keep and administer other objects
Algorithm procedure that is able to work on different containers
Iterator pointer that is able to iterate through the contents of a container
Function Object a class that has the function-call operator() defined
Adaptor encapsulates a component to provide another interface (e.g: stack out of a list)
o Containers are the STL objects that actually store data.
o Each container has defined for it an allocator.
o Allocators manage memory allocation for a container.
o Iterators are used to access elements within the containers.
o Once the data is stored in a container, it can be manipulated by any of the available algorithm.
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v1(5,0); // Vector of size 5, each 0 int data, i;
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
Lists
o The listclass supports a bidirectional, linear list. The file <list>should be included.
o A list can be accessed sequential only whereas vector can be accessed randomly.
o Some member functions applicable to list are:
Member Fn Description
begin() Returns an Iterator to the first element in the list
clear() Removes all elements from the list
empty() Returns true if the invoking list is empty
end() Returns an Iterator to the end of the list
erase(I) Removes an element pointed to by the Iterator I
erase(st, end) Removes all elements in the range from st to end
insert(I, val) Inserts val before the Iterator I and returns an Iterator
pop_back() Removes the last element in the list
pop_front() Removes the first element in the list
push_back(val) Adds an element with value val at the end of the list
push_front(val) Adds an element with value val at the start of the list
size() Returns number of elements currently in the list
back() Returns a reference to the last element in the list
front() Returns a reference to the first element in the list
remove(val) Removes elements with value val from the list
reverse() Reverses the invoking list
sort() Sorts the list in ascending order
merge(L) Merges two ordered list.
#include <iostream>
#include <list>
using namespace std;
int main()
{
list <int> l2,l3;
list <int>::iterator first;
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
l3.sort();
l2.merge(l3);
cout << "\n Merged List " ; first = l2.begin(); while(first != l2.end())
cout << *first++ << " ";
return 0;
}
Maps
o The mapclass supports an associative container in which unique key is mapped with values
o The map class does not allow duplicate keys. The file <map>should be included.
o Some commonly used member functions of map class are:
Member Fn Description
begin() Returns an Iterator to the first element in the map
clear() Removes all elements from the map
empty() Returns true if the invoking map is empty
end() Returns an Iterator to the end of the map
count(K) Returns whether a key K occurs in the map
erase(I) Removes an element pointed to by the Iterator I
erase(I1,I2) Removes all elements in the range pointed to by the Iterators I1 and I2
erase(val) Removes from the map that have keys with value val
find(K) Returns an iterator that points to element whose first component equals
the key. If no such element is found, then the pointer points to end()
insert(I,val) Updates value of the element pointed by Iterator I with val
insert(pair<Kt,Vt>, Inserts a key and its associated value.
(key,val))
size() Returns number of elements currently in the map
#include <iostream>
#include <map>
using namespace std;
int main()
{
map <char, int> m1;
map <char, int>::iterator ptr;
char ch;
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
o STL algorithms are standalone template functions that can be used either with container classes or
arrays.
o Algorithms are generic and are parameterized by iterator types. Hence separated from particular
implementations of data structures.
o To have access to STL algorithms, include <algorithm>in the program.
o It is classified into four groups namely: mutating, non-mutating, sorting and numeric
operations. Some of them are:
Algorithm Description
count() Returns no. of elements in the range that match a given value
count_if() Returns no. of elements in the range for which the given function is true
find() Finds first occurrence of a value in the given sequence
for_each() Apply an operation to each element
copy() Copies the given sequence
remove() Deletes elements with the specified value
replace() Replaces elements with the specified value.
reverse() Reverses the order of elements in the specified range
swap() Swap two elements
transform() It transforms all the elements in the range according to given function
sort() Sorts values in the given range
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
float fdata[] = { 19.2, 87.4, -33.6, 55.0, 42.2 };
sort(fdata, fdata+5, greater<float>()); // sort the array for(int j=0; j<5; j++)
cout << fdata[j] << " " ;
return 0;
}
STL Adaptors
o Adaptors are template classes that provide interface mappings.
o Adaptors are classes that are based on other classes to implement a new functionality.
o Stack—A stack can be instantiated either with a vector, a list or a deque. The member functions
empty, size, top, pushand popare accessible to the user.
stack < deque<int> > s1;
o Queue—A queue can be instantiated with a listor a deque. Its public member functions are
empty, size, front, back, push and pop. As with the stack, two queues can be
compared using operator ==and operator <.
queue < list <int> > q1;
o Priority queue—A priority queue can be instantiated with a vector. A priority queue holds
the elements added by pushsorted by using a function object.
priority_queue < vector <int>, less <int> > pq1;
iterator
o Iterators are smart pointers used to access / modify elements of a container class.
o Operators ++and *are overloaded
o STL implements five different types of iterators.
o random access iteratorsʊStore and retrieve values with random access.
o bidirectional iteratorsʊcan store and write in both forward and backward
o forward iteratorsʊcan read, write, and move in forward direction
o input iteratorsʊcan only be used to read a sequence of values in forward direction
o output iteratorsʊcan only be used to write a sequence of values in forward direction
o For example, vector uses random access iterator, whereas list has only a bidirectional iterator.
o Iterators determine which algorithms can be used with which containers.
o Iterators allow generality. For example, an algorithm to reverse a sequence implemented
using bidirectional iterators can be used on lists, vectors and deques.
manipulator.
CS6301 Programming & Data Structures -II Page 19
jntuworldupdates.org Specworld.in
Smartzworld.com Smartworld.asia
Lecture Notes
Manipulators Description
Endl Output a newline character.
setfill(ch) Set the fill character to ch.
setiosflags(f) Turn on the flags specified in flg. Flag may be ios::right, ios::left ios::fixed,
ios::hex, ios::oct, etc.
setprecision(p) Sets the number of digits of floating point precision.
setw(w) Sets the field width to w.
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout << setprecision(2) << setw(10) << setfill('*')
<< setiosflags(ios::right|ios::fixed);
cout << 2343.4 << endl; // ***2343.40 return 0;
}
jntuworldupdates.org Specworld.in