SlideShare a Scribd company logo
Concept Of Object Oriented
Programming
oop is an approach or a Programming pattern where the programs are
structured around objects rather than functions and logic. It makes the
data partitioned into two memory areas, i.e., data and functions, and
helps make the code flexible and modular.
Object-oriented programming mainly focuses on objects that are
required to be manipulated. In OOPs, it can represent data as objects
that have attributes and functions.
Basic Object-Oriented
Programming
 Object-An O Object can be defined as an entity that has a state and
behavior, or in other words, anything that exists physically in the
world is called an object. It can represent a dog, a person, a table,
etc. An object means the combination of data and programs, which
further represent an entity.
 Classes-Class can be defined as a blueprint of the object. It is basically
a collection of objects which act as building blocks.

Abstraction- Abstraction helps in the data hiding process. It helps in
displaying the essential features without showing the details or the
functionality to the user. It avoids unnecessary information or
irrelevant details and shows only that specific part which the user
wants to see.
Basic Object-Oriented Programming
 Encapsulation- The wrapping up of data and functions together in a single unit is
known as encapsulation. It can be achieved by making the data members' scope
private and the member function’s scope public to access these data members.
Encapsulation makes the data non-accessible to the outside world.
 Inheritance- Inheritance is the process in which two classes have an is-a relationship
among each other and objects of one class acquire properties and features of the
other class. The class which inherits the features is known as the child class, and the
class whose features it inherited is called the parent class. For example, Class Vehicle is
the parent class, and Class Bus, Car, and Bike are child classes.
 Polymorphism- It means many forms. It is the ability to take more than one form. It is
a feature that provides a function or an operator with more than one definition. It can
be implemented using function overloading, operator overload, function overriding,
virtual function.
Object Oriented Programming
Advantages of OOPs
There are various advantages of object-oriented programming.
 OOPs provide reusability to the code and extend the use of existing
classes.
 In OOPs, it is easy to maintain code as there are classes and objects,
which helps in making it easy to maintain rather than restructuring.
 It also helps in data hiding, keeping the data and information safe
from leaking or getting exposed.
 Object-oriented programming is easy to implement.
Inheritance, Polymorphism, and Virtual
Functions
What Is Inheritance?
• Provides a way to create a new class from an
existing class
• The new class is a specialized version of the
existing class
Example: Insect Taxonomy
The "is a" Relationship
• Inheritance establishes an "is a"
relationship between classes.
– A poodle is a dog
– A car is a vehicle
– A flower is a plant
– A football player is an athlete
Inheritance – Terminology and Notation in C+
+
• Base class (or parent) – inherited from
• Derived class (or child) – inherits from the base class
• Notation:
class Student // base class
{
. . .
};
class UnderGrad : public student
{ // derived class
. . .
};
Back to the ‘is a’ Relationship
• An object of a derived class 'is a(n)' object of
the base class
• Example:
– an UnderGrad is a Student
– a Mammal is an Animal
• A derived object has all of the characteristics
of the base class
What Does a Child Have?
An object of the derived class has:
• all members defined in child class
• all members declared in parent class
An object of the derived class can use:
• all public members defined in child class
• all public members defined in parent
class
Protected Members and Class
Access
• protected member access
specification: like private, but
accessible by objects of derived class
• Class access specification: determines
how private, protected, and
public members of base class are
inherited by the derived class
Class Access Specifiers
1) public – object of derived class can be
treated as object of base class (not vice-versa)
2) protected – more restrictive than
public, but allows derived classes to know
details of parents
3) private – prevents objects of derived class
from being treated as objects of base class.
Inheritance vs. Access
private: x
protected: y
public: z
private: x
protected: y
public: z
private: x
protected: y
public: z
Base class members
x is inaccessible
private: y
private: z
x is inaccessible
protected: y
protected: z
x is inaccessible
protected: y
public: z
How inherited base class
members
appear in derived class
private
base class
protecte
d
base class
public
base class
Inheritance vs. Access
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
class Test : public Grade
When Test class inherits
from Grade class using
public class access, it
looks like this:
private members:
int numQuestions:
float pointsEach;
int numMissed;
public members:
Test(int, int);
void setScore(float);
float getScore();
char getLetter();
Inheritance vs. Access
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
When Test class inherits
from Grade class using
protected class access, it
looks like this:
private members:
int numQuestions:
float pointsEach;
int numMissed;
public members:
Test(int, int);
protected members:
void setScore(float);
float getScore();
float getLetter();
class Test : protected Grade
Inheritance vs. Access
private members:
int numQuestions:
float pointsEach;
int numMissed;
void setScore(float);
float getScore();
float getLetter();
public members:
Test(int, int);
private members:
char letter;
float score;
void calcGrade();
public members:
void setScore(float);
float getScore();
char getLetter();
class Grade
private members:
int numQuestions;
float pointsEach;
int numMissed;
public members:
Test(int, int);
When Test class inherits
from Grade class using
private class access, it
looks like this:
class Test : private Grade
Constructors and Destructors in Base and
Derived Classes
• Derived classes can have their own
constructors and destructors
• When an object of a derived class is created,
the base class’s constructor is executed first,
followed by the derived class’s constructor
• When an object of a derived class is
destroyed, its destructor is called first, then
that of the base class
Constructors and Destructors in Base and
Derived Classes
Constructors and Destructors in Base and
Derived Classes
Constructors and Destructors in Base and
Derived Classes
Passing Arguments to
Base Class Constructor
• Allows selection between multiple base class
constructors
• Specify arguments to base constructor on
derived constructor heading:
Square::Square(int side) :
Rectangle(side,
side)
• Can also be done with inline constructors
• Must be done if base class has no default
constructor
Passing Arguments to
Base Class Constructor
Square::Square(int side):Rectangle(side,side)
derived class constructor base class constructor
derived constructor
parameter
base constructor
parameters
Redefining Base Class Functions
• Redefining function: function in a derived class
that has the same name and parameter list as
a function in the base class
• Typically used to replace a function in base
class with different actions in derived class
Redefining Base Class Functions
• Not the same as overloading – with
overloading, parameter lists must be different
• Objects of base class use base class version of
function; objects of derived class use derived
class version of function
Base Class
Derived Class
Redefined setScore function
Driver Program
Problem with Redefining
• Consider this situation:
– Class BaseClass defines functions x() and y().
x() calls y().
– Class DerivedClass inherits from BaseClass and
redefines function y().
– An object D of class DerivedClass is created and
function x() is called.
– When x() is called, which y() is used, the one
defined in BaseClass or the the redefined one in
DerivedClass?
Problem with Redefining
BaseClass
DerivedClass
void X();
void Y();
void Y();
DerivedClass D;
D.X();
Object D invokes function X()
In BaseClass. Function X()
invokes function Y() in BaseClass, not
function Y() in DerivedClass,
because function calls are bound at
compile time. This is static binding.
Class Hierarchies
• A base class can be derived from another base
class.
Class Hierarchies
• Consider the GradedActivity, FinalExam,
PassFailActivity, PassFailExam hierarchy in Chapter
15.
Polymorphism and Virtual Member Functions
• Virtual member function: function in base class that
expects to be redefined in derived class
• Function defined with key word virtual:
virtual void Y() {...}
• Supports dynamic binding: functions bound at run
time to function that they call
• Without virtual member functions, C++ uses static
(compile time) binding
Polymorphism and Virtual Member Functions
Because the parameter in the displayGrade function is a GradedActivity
reference variable, it can reference any object that is derived from
GradedActivity. That means we can pass a GradedActivity object, a
FinalExam object, a PassFailExam object, or any other object that is
derived from GradedActivity.
A problem occurs in Program 15-10 however...
Overview of Object Oriented Programming using C++
As you can see from the example output, the getLetterGrade member
function returned ‘C’ instead of ‘P’. This is because the GradedActivity
class’s getLetterGrade function was executed instead of the
PassFailActivity class’s version of the function.
Static Binding
• Program 15-10 displays 'C' instead of 'P'
because the call to the getLetterGrade
function is statically bound (at compile time)
with the GradedActivity class's version of the
function.
We can remedy this by making the function
virtual.
Virtual Functions
• A virtual function is dynamically bound to calls
at runtime.
At runtime, C++ determines the type of object
making the call, and binds the function to the
appropriate version of the function.
Virtual Functions
• To make a function virtual, place the virtual
key word before the return type in the base
class's declaration:
virtual char getLetterGrade() const;
• The compiler will not bind the function to
calls. Instead, the program will bind them at
runtime.
Updated Version of GradedActivity
The function
is now
virtual.
The function also becomes
virtual in all derived classes
automatically!
Polymorphism
If we recompile our program with the updated versions of
the classes, we will get the right output, shown here:
(See Program 15-11 in the book.)
This type of behavior is known as polymorphism. The term
polymorphism means the ability to take many forms.
Program 15-12 demonstrates polymorphism by passing
objects of the GradedActivity and PassFailExam classes to
the displayGrade function.
Overview of Object Oriented Programming using C++
Overview of Object Oriented Programming using C++
Polymorphism Requires References or
Pointers
• Polymorphic behavior is only possible when an
object is referenced by a reference variable or
a pointer, as demonstrated in the
displayGrade function.
Base Class Pointers
• Can define a pointer to a base class object
• Can assign it the address of a derived class
object
Base Class Pointers
• Base class pointers and references only know about
members of the base class
– So, you can’t use a base class pointer to call a derived class
function
• Redefined functions in derived class will be ignored
unless base class declares the function virtual
Redefining vs. Overriding
• In C++, redefined functions are statically
bound and overridden functions are
dynamically bound.
So, a virtual function is overridden, and a
non-virtual function is redefined.
Virtual Destructors
• It's a good idea to make destructors
virtual if the class could ever become a
base class.
• Otherwise, the compiler will perform
static binding on the destructor if the
class ever is derived from.
• See Program 15-14 for an example
Abstract Base Classes and Pure Virtual
Functions
• Pure virtual function: a virtual member
function that must be overridden in a derived
class that has objects
• Abstract base class contains at least one pure
virtual function:
virtual void Y() = 0;
• The = 0 indicates a pure virtual function
• Must have no function definition in the base
class
Abstract Base Classes and Pure Virtual
Functions
• Abstract base class: class that can have no
objects. Serves as a basis for derived classes
that may/will have objects
• A class becomes an abstract base class when
one or more of its member functions is a pure
virtual function
Multiple Inheritance
• A derived class can have more than one base
class
• Each base class can have its own access
specification in derived class's definition:
class cube : public square,
public rectSolid;
class
square
class
rectSolid
class
cube
Multiple Inheritance
• Problem: what if base classes have member
variables/functions with the same name?
• Solutions:
– Derived class redefines the multiply-defined function
– Derived class invokes member function in a particular
base class using scope resolution operator ::
• Compiler errors occur if derived class uses base
class function without one of these solutions
TEMPLATES AND FILE OPERATIONS
Templates, Function templates, class Templates,
Overloading of Template Functions Member
function Templates,
File stream operations-
ostream,ifstream,fstream,File Access Modes
File position pointer – fseek get,fseek put,ftell get,
ftell put, Sequential Input and Output operations
Random Access, Error handling during file
operation.
Templates in C++
• It is a simple and powerful tool in C++
• simple idea is to pass data type as a parameter so that
we don’t need to write the same code for different data
types.
• Templates are often used in larger codebase for the
purpose of code reusability and flexibility of the
programs.
• The concept of templates can be used in two different
ways:
• Function Templates
• Class Templates
How it works?
• Templates are expanded at compiler
time. This is like macros.
• Difference between Macro and
Template is compiler does type
checking before template expansion.
Function Templates
• A function template works in a similar to a normal function,
with one key difference.
• A single function template can work with different data
types at once but, a single normal function can only work
with one set of data types.
• Normally, if you need to perform identical operations on two
or more types of data, you use function overloading to create
two functions with the required function declaration.
• However, a better approach would be to use function
templates because you can perform the same task writing
less and maintainable code.
How to declare a function template?
A function template starts with the keyword template followed by
template parameter/s inside < > which is followed by function
declaration.
template <typename T>
T someFunction(T arg)
{
... .. ...
}
• In the above code, T is a template argument that accepts different
data types (int, float), and class is a keyword.
• You can also use keyword typename instead of class in the above
example.
• When, an argument of a data type is passed to someFunction( ),
compiler generates a new version of someFunction() for the given
data type.
Overview of Object Oriented Programming using C++
Class Templates
• Like function templates, you can also create class templates
for generic class operations.
• Sometimes, you need a class implementation that is same
for all classes, only the data types used are different.
• Normally, you would need to create a different class for
each data type OR create different member variables and
functions within a single class.
• This will unnecessarily bloat your code base and will be
hard to maintain, as a change is one class/function should
be performed on all classes/functions.
• However, class templates make it easy to reuse the same
code for all data types.
How to declare a class
template?
template <class T>
class className
{ ... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
• In the above declaration, T is the template argument which is a
placeholder for the data type used.
• Inside the class body, a member variable var and a member
function someOperation() are both of type T.
How to create a class template
object?
To create a class template object, you need to define the
data
type inside a < > when creation.
className<dataType> classObject;
For example:
className<int> classObject;
className<float> classObject;
className<string>
classObject;
Overloading of Template
Functions
• You may overload a function template either by a non-
template function or by another function template.
• If you call the name of an overloaded function template, the
compiler will try to deduce its template arguments and
check its explicitly declared template arguments. If
successful, it will instantiate a function template
specialization, then add this specialization to the set of
candidate functions used in overload resolution.
• The compiler proceeds with overload resolution, choosing
the most appropriate function from the set of candidate
functions. Non-template functions take precedence over
template
Files - Introduction
• Computer programs are associated to work with files as
it helps in storing data & information permanently.
• File - itself a bunch of bytes stored on some storage
devices.
• In C++ this is achieved through a component header file
called fstream.h
• The I/O library manages two aspects- as interface
and for transfer of
data.
• The library predefine a set of operations for all file
related handling through certain classes.
File Handling using File Streams in C++
File represents storage medium for storing data or information. Streams
refer to sequence of bytes. In Files we store data i.e. text or binary data
permanently and use these data to read or write in the form of input output
operations by transferring bytes of data. So we use the term File
Streams/File handling. We use the header file <fstream>
1.
2.
3.
ofstream: It represents output Stream and this is used for writing in
files.
ifstream: It represents input Stream and this is used for
reading
from files.
fstream: It represents both output Stream and input Stream. So it
can read from files and write to files.
Operations in File Handling:
Creating a file
Reading data
Writing new data
Closing a file
: open()
: read()
: write()
: close()
• Streams act as an interface between files and programs.
• They represent as a sequence of bytes and deals with the flow of
data.
• Every stream is associated with a class having member functions
and operations for a particular kind of data flow.
• File -> Program ( Input stream) - reads
• Program ->File (Output stream) – write
• All designed into fstream.h and hence needs to be included in all
file handling programs.
• To use the fstream library, include both the standard <iostream>
AND the <fstream> header file:
File Streams in C++
Stream Classes for File Operations in C++
File Access Modes
C++ File Pointers
Every file maintains two pointers called
• get_pointer (in input mode file)
• put_pointer (in output mode file)
which tells the current position in the file where reading or
writing will takes place respectively
A file pointer in this context is not like a C++ pointer but it
works like a book-mark in a book.
These pointers help attain random access in file. That means
moving directly to any location in the file instead of moving
through it sequentially.
Sequential Access Vs Random File Access
Sequential Access Random Access
In a sequential-access file, it is possible
to read and write information
sequentially, starting from the
beginning of the file.
A random-access data file enables you
to read or writeinformation anywhere
in the file.
To go from point A to point Z in a
sequential-access system, you must
pass through all intervening points.
In a random-access system, you can
jump directly to point Z.
Random access is sometimes called
direct access.
If information is accessed in the same
order, a sequential-access file is faster.
To access information randomly,
random access is better
Random Access Files
There may be situations where random access in the best choice.
For example, if you have to modify a value in record no 21, then using
random access techniques, you can place the file pointer at the beginning
of record 21 and then straight-way process the record.
If sequential access is used, then you'll have to unnecessarily go through
first twenty records in order to reach at record 21.
The seekg(), seekp(), tellg() and tellp() Functions
In C++, random access is achieved by manipulating seekg(),
seekp(), tellg() and tellp() functions.
The seekg() and tellg() functions allow you to set and examine the
get_pointer, and the seekp() and tellp() functions perform these
operations on the put_pointer.
The seekg() and tellg() functions are for input streams
(ifstream) and seekp() and tellp() functions are for output
streams (ofstream).
Overview of Object Oriented Programming using C++
Error handling during file operation.
Error handling refers to the response and recovery procedures from
error conditions present in a software application. In other words, it
is the process comprised of anticipation, detection and resolution of
application errors, programming errors or communication errors.
It is possible that an error may occur during I/O operations on a file.
Typical error situations include:
1. Trying to read beyond the end-of-file mark.
2. Device overflow means no space in the disk for storing data.
3. Trying to use a file that has not been opened.
4. Trying to perform operation on a file, when the file is opened for
another type of operation.
5. Opening a file with an invalid filename.
6. Try to read a file with no data in it.
If we fail to check such read and write errors, a program may behave
abnormally when an error occurs. An unchecked error may result in
a premature termination of the program or incorrect output.
Function Meaning
int bad()
Returns a non-zero value if an invalid operation is attempted or
any unrecoverable error has occurred. However, if it is zero (false
value), it may be possible to recover from any other error reported
and continue operations.
int eof()
Returns non-zero (true value) if end-of-file is encountered while
reading; otherwise returns zero (false value).
int fail()
Returns non-zero (true) when an input or output operation has
failed.
int good()
Returns non-zero (true) if no error has occurred. This means, all
the above functions are false. For example, if fin.good() is true,
everything is okay with the stream named as fin and we can
proceed to perform I/O operations. When it returns zero, no
further operations can be carried out.
clear() Resets the error state so that further operations can be attempted.
Following table lists these error handling functions and their meaning :
EXCEPTION HANDLING AND STL
Exception handing mechanism, Throwing
mechanism catching mechanism, Rethrowing
an exception, C++ Standard Exception
Library, runtime error, logic failures, user
defined exceptions, Exception handling in
inheritance, specifying exceptions.
C++ standard STL.- Containers, Algorithms,
Iterators – Standard function library
Exception in Programs
• An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
• Many different kinds of errors can cause exceptions: problems
ranging from serious hardware errors, such as a hard disk
crash, to simple programming errors, such as trying to access
an out-of-bounds array element.
Exception in C++
• A C++ exception is a response to an exceptional circumstance
that arises while a program is running, such as an attempt to
divide by zero.
• Exceptions provide a way to transfer control from one part of a
program to another.
• C++ exception handling is built upon three keywords: try,
catch, and throw.
Exception in C++ - Continued
1. throw − A program throws an exception when a problem shows
up. This is done using a throw keyword.
2. catch − A program catches an exception with an exception
handler at the place in a program where you want to handle the
problem. The catch keyword indicates the catching of an
exception.
3. try − A try block identifies a block of code for which particular
exceptions will be activated. It's followed by one or more catch
blocks.
#include <stdexcept> // To use built in Exception Library
try
{ // protected code }
catch( ExceptionName e1 ) { // catch block }
catch( ExceptionName e2 ) { // catch block }
catch( ExceptionName eN ) { // catch block }
C++ Standard Exceptions
C++ provides a list of standard exceptions defined in <exception>
which we can use in our programs. These are arranged in a parent-
child class hierarchy shown below
Exception Programs
Runtime Errors & Logic Failures - Example
• Divide by Zero Exception
• Array Index Out of Bounds Exception
• Overflow Error
Assignment - 1
Write a calculator program in C++ with necessary
exception handling mechanisms
Throwing mechanism & Catching mechanism
The exception handler is declared with the catch keyword
immediately after the closing brace of the try block. The syntax for
catch is similar to a regular function with one parameter. The type
of this parameter is very important, since the type of the argument
passed by the throw expression is checked against it, and only in the
case they match, the exception is caught by that handler.
Multiple handlers (i.e., catch expressions) can be chained; each one
with a different parameter type. Only the handler whose argument
type matches the type of the exception specified in the throw
statement is executed.
If an ellipsis (...) is used as the parameter of catch, that handler will
catch any exception no matter what the type of the exception
thrown. This can be used as a default handler that catches all
exceptions not caught by other handlers
C++ User-Defined Exceptions
The new exception can be defined by overriding and inheriting
exception class functionality.
#include <iostream>
#include <exception>
using namespace std;
//Creating a user defined exception class
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!n";
}
};
Rethrowing an exception
• Rethrowing an expression from within an exception handler can
be done by calling throw, by itself, with no exception.
• This causes current exception to be passed on to an outer
try/catch sequence.
• An exception can only be rethrown from within a catch block.
• When an exception is rethrown, it is propagated outward to the
next catch block.
void MyHandler()
{
try
{
throw "Hello";
}
catch (const char*)
{
cout <<"Caught exception inside MyHandlern";
throw; //rethrow char* out of function
}
Exception Handling in Inheritance
Exception Handling – catching base and derived classes as exceptions:
If both base and derived classes are caught as exceptions then catch
block of derived class must appear before the base class.
If we put base class first then the derived class catch block will never
be reached. For example, following C++ code prints “Caught Base
Exception”
In Java, catching a base class exception before derived is not allowed
by the compiler itself.
In C++, compiler might give warning about it, but compiles the
code.
#include<iostream>
using namespace std;
class Base {};
class Derived: public Base {};
int main()
{
Derived d;
// some other stuff
try {
// Some monitored code
throw d;
}
catch(Base b) {
cout<<"Caught Base Exception";
}
catch(Derived d) { //This catch block is NEVER executed
cout<<"Caught Derived Exception";
}
getchar();
return 0;
}
In this C++ code, if we change
the order of catch statements
then both catch statements
become reachable.
Exception specifications (throw, noexcept) (C++)
• Exception specifications are a C++ language feature that
indicate the programmer's intent about the exception types that
can be propagated by a function.
• You can specify that a function may or may not exit by an
exception by using an exception specification.
• The compiler can use this information to optimize calls to the
function, and to terminate the program if an unexpected
exception escapes the function.
• If exception handling is used in an application, there must be a
function in the call stack that handles thrown exceptions before
they exit the outer scope of a function marked noexcept,
noexcept(true), or throw()
• Syntax
void MyFunction(int i) throw();
void MyFunction(int i) noexcept;
Assignment / Lab Excercise
Write a program that converts dates from numerical
month/day format to alphabetic month/day (for example,
1/31 or 01/31 corresponds to January 31).
You will define two exception classes, one called
MonthErrorand another called DayError.
If the user enters anything other than a legal month
number (integers from 1 to 12), then your program will
throw and catch a MonthError.
Similarly, if the user enters anything other than a valid
day number (integers from 1 to either 29, 30, or 31,
depending on the month), then your program will throw
and catch a DayError. To keep things simple, always allow
29 days for February.
Overview of Object Oriented Programming using C++
Introduction to the Standard Template Library
The Standard Template Library, or STL, is a C++ library of
container classes, algorithms, and iterators; it provides many of the
basic algorithms and data structures of computer science.
The STL is a generic library, meaning that its components are
heavily parameterized: almost every component in the STL is a
template. You should make sure that you understand how
templates work in C++ before you use the STL.
The STL includes the classes vector, list, deque, set, multiset, map,
multimap, hash_set, hash_multiset, hash_map, and
hash_multimap. Each of these classes is a template, and can be
instantiated to contain any type of object
STL has four components
1. Algorithms
2. Containers
3. Functions
4. Iterators
Algorithms The header algorithm defines a collection of functions
especially designed to be used on ranges of elements.They act
on containers and provide means for various operations for the
contents of the containers.
Algorithm
Sorting
Searching
Important STL Algorithms
Useful Array algorithms
Partition Operations
Containers Containers or container classes store objects and data. There
are in total seven standard “first-class” container classes and
three container adaptor classes and only seven header files that
provide access to these containers or container adaptors.
Refer to types of containers in slide 16
Functions The STL includes classes that overload the function call
operator. Instances of such classes are called function objects or
functors. Functors allow the working of the associated function
to be customized with the help of parameters to be passed.
Vector in C++ STL
• Vectors are same as dynamic arrays with the ability to resize
itself automatically when an element is inserted or deleted,
with their storage being handled automatically by the
container.
• Vector elements are placed in contiguous storage so that they
can be accessed and traversed using iterators. In vectors, data is
inserted at the end.
• Inserting at the end takes differential time, as sometimes there
may be a need of extending the array.
• Removing the last element takes only constant time because no
resizing happens.
• Inserting and erasing at the beginning or in the middle is linear
in time.
Vector in C++ STL
Certain functions associated with the vector are:
Iterators
• begin() – Returns an iterator pointing to the first element in the vector
• end() – Returns an iterator pointing to the theoretical element that
follows the last element in the vector
• rbegin() – Returns a reverse iterator pointing to the last element in the
vector (reverse beginning). It moves from last to first element
• rend() – Returns a reverse iterator pointing to the theoretical element
preceding the first element in the vector (considered as reverse end)
• cbegin() – Returns a constant iterator pointing to the first element in
the vector.
• cend() – Returns a constant iterator pointing to the theoretical element
that follows the last element in the vector.
• crbegin() – Returns a constant reverse iterator pointing to the last
element in the vector (reverse beginning). It moves from last to first
element
• crend() – Returns a constant reverse iterator pointing to the theoretical
element preceding the first element in the vector (considered as reverse
end)
List in C++ STL
Lists are sequence containers that allow constant time insert and erase
operations anywhere within the sequence, and iteration in both directions.
List containers are implemented as doubly-linked lists; Doubly linked lists
can store each of the elements they contain in different and unrelated
storage locations. The ordering is kept internally by the association to each
element of a link to the element preceding it and a link to the element
following it.
They are very similar to forward_list: The main difference being that
forward_list objects are single-linked lists, and thus they can only be iterated
forwards, in exchange for being somewhat smaller and more efficient.
Compared to other base standard sequence containers (array, vector and
deque), lists perform generally better in inserting, extracting and moving
elements in any position within the container for which an iterator has
already been obtained, and therefore also in algorithms that make intensive
use of these, like sorting algorithms.
List in C++ - Sequence Containers
Some more useful functions are discussed in this article
1. emplace(position, value) :- This function is used to insert an element
at the position specified.
2. emplace_back(value) :- This function adds value at end of list.
3. emplace_front :- This function adds value at beginning of list
4. merge(list2) :- This function is used to merge list2 with list1. If both
the lists are in sorted order, then the resulting list is also sorted.
5. remove_if(condition) :- This function removes the element from list on
the basis of condition given in its argument
6. unique() :- This function is used to delete the repeated occurrences of
the number. List has to be sorted for this function to get executed.
7. splice(position, list2) :- This function is used to transfer elements from
one list into another.
8. swap(list2) :- This function is used to swap one list element with other.
Set in C++ STL
• Sets are containers that store unique elements following a specific order.
In a set, the value of an element also identifies it (the value is itself the
key, of type T), and each value must be unique. The value of the
elements in a set cannot be modified once in the container (the elements
are always const), but they can be inserted or removed from the
container.
• Internally, the elements in a set are always sorted following a specific
strict weak ordering criterion indicated by its internal comparison object
(of type Compare).
• Set containers are generally slower than unordered_set containers to
access individual elements by their key, but they allow the direct
iteration on subsets based on their order.
• Sets are typically implemented as binary search trees.
Set in C++ STL
Some basic functions associated with Set:
• begin() – Returns an iterator to the first element in the set.
• end() – Returns an iterator to the theoretical element that follows last element in
the set.
• size() – Returns the number of elements in the set.
• max_size() – Returns the maximum number of elements that the set can hold.
• empty() – Returns whether the set is empty.
• count(const g) – Returns 1 or 0 based on the element ‘g’ is present in the set or
not.
• lower_bound(const g) – Returns an iterator to the first element that is equivalent
to ‘g’ or definitely will not go before the element ‘g’ in the set.
• upper_bound(const g) – Returns an iterator to the first element that is
equivalent to ‘g’ or definitely will go after the element ‘g’ in the set.
• equal_range()– The function returns an iterator of pairs. (key_comp). The pair
refers to the range that includes all the elements in the container which have a
key equivalent to k.
• emplace()– This function is used to insert a new element into the set container,
only if the element to be inserted is unique and does not already exists in the set.
Ad

More Related Content

Similar to Overview of Object Oriented Programming using C++ (20)

introduction-to-object-oriented-programming.ppt
introduction-to-object-oriented-programming.pptintroduction-to-object-oriented-programming.ppt
introduction-to-object-oriented-programming.ppt
hijat789
 
introduction-to-object-oriented-programming.ppt
introduction-to-object-oriented-programming.pptintroduction-to-object-oriented-programming.ppt
introduction-to-object-oriented-programming.ppt
RamadossSundaramoort1
 
introduction-to-object-oriented-programming.ppt
introduction-to-object-oriented-programming.pptintroduction-to-object-oriented-programming.ppt
introduction-to-object-oriented-programming.ppt
kaavyashruthi
 
Object Oriented Programming fundamentals.pptx
Object Oriented Programming fundamentals.pptxObject Oriented Programming fundamentals.pptx
Object Oriented Programming fundamentals.pptx
sanaiftikhar23
 
oops-123991513147-phpapp02.pdf
oops-123991513147-phpapp02.pdfoops-123991513147-phpapp02.pdf
oops-123991513147-phpapp02.pdf
ArpitaJana28
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
AshutoshTrivedi30
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
Army Public School and College -Faisal
 
java part 1 computer science.pptx
java part 1 computer science.pptxjava part 1 computer science.pptx
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
OOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHatOOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
Oops
OopsOops
Oops
PRABHAHARAN429
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
Synapseindiappsdevelopment
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
baabtra.com - No. 1 supplier of quality freshers
 
Lab 4 (1).pdf
Lab 4 (1).pdfLab 4 (1).pdf
Lab 4 (1).pdf
MohammedAlobaidy16
 
oopusingc.pptx
oopusingc.pptxoopusingc.pptx
oopusingc.pptx
MohammedAlobaidy16
 
Unit i
Unit iUnit i
Unit i
snehaarao19
 
oops-1
oops-1oops-1
oops-1
snehaarao19
 
Only oop
Only oopOnly oop
Only oop
anitarooge
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introduction
sandeep54552
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 

Recently uploaded (20)

Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Modelling of Concrete Compressive Strength Admixed with GGBFS Using Gene Expr...
Journal of Soft Computing in Civil Engineering
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Machine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATIONMachine Learning basics POWERPOINT PRESENETATION
Machine Learning basics POWERPOINT PRESENETATION
DarrinBright1
 
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdfPRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Academy - Functional Modeling In Action with PRIZ.pdf
PRIZ Guru
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software ApplicationsJacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia - Excels In Optimizing Software Applications
Jacob Murphy Australia
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
Ad

Overview of Object Oriented Programming using C++

  • 1. Concept Of Object Oriented Programming oop is an approach or a Programming pattern where the programs are structured around objects rather than functions and logic. It makes the data partitioned into two memory areas, i.e., data and functions, and helps make the code flexible and modular. Object-oriented programming mainly focuses on objects that are required to be manipulated. In OOPs, it can represent data as objects that have attributes and functions.
  • 2. Basic Object-Oriented Programming  Object-An O Object can be defined as an entity that has a state and behavior, or in other words, anything that exists physically in the world is called an object. It can represent a dog, a person, a table, etc. An object means the combination of data and programs, which further represent an entity.  Classes-Class can be defined as a blueprint of the object. It is basically a collection of objects which act as building blocks.  Abstraction- Abstraction helps in the data hiding process. It helps in displaying the essential features without showing the details or the functionality to the user. It avoids unnecessary information or irrelevant details and shows only that specific part which the user wants to see.
  • 3. Basic Object-Oriented Programming  Encapsulation- The wrapping up of data and functions together in a single unit is known as encapsulation. It can be achieved by making the data members' scope private and the member function’s scope public to access these data members. Encapsulation makes the data non-accessible to the outside world.  Inheritance- Inheritance is the process in which two classes have an is-a relationship among each other and objects of one class acquire properties and features of the other class. The class which inherits the features is known as the child class, and the class whose features it inherited is called the parent class. For example, Class Vehicle is the parent class, and Class Bus, Car, and Bike are child classes.  Polymorphism- It means many forms. It is the ability to take more than one form. It is a feature that provides a function or an operator with more than one definition. It can be implemented using function overloading, operator overload, function overriding, virtual function.
  • 5. Advantages of OOPs There are various advantages of object-oriented programming.  OOPs provide reusability to the code and extend the use of existing classes.  In OOPs, it is easy to maintain code as there are classes and objects, which helps in making it easy to maintain rather than restructuring.  It also helps in data hiding, keeping the data and information safe from leaking or getting exposed.  Object-oriented programming is easy to implement.
  • 6. Inheritance, Polymorphism, and Virtual Functions
  • 7. What Is Inheritance? • Provides a way to create a new class from an existing class • The new class is a specialized version of the existing class
  • 9. The "is a" Relationship • Inheritance establishes an "is a" relationship between classes. – A poodle is a dog – A car is a vehicle – A flower is a plant – A football player is an athlete
  • 10. Inheritance – Terminology and Notation in C+ + • Base class (or parent) – inherited from • Derived class (or child) – inherits from the base class • Notation: class Student // base class { . . . }; class UnderGrad : public student { // derived class . . . };
  • 11. Back to the ‘is a’ Relationship • An object of a derived class 'is a(n)' object of the base class • Example: – an UnderGrad is a Student – a Mammal is an Animal • A derived object has all of the characteristics of the base class
  • 12. What Does a Child Have? An object of the derived class has: • all members defined in child class • all members declared in parent class An object of the derived class can use: • all public members defined in child class • all public members defined in parent class
  • 13. Protected Members and Class Access • protected member access specification: like private, but accessible by objects of derived class • Class access specification: determines how private, protected, and public members of base class are inherited by the derived class
  • 14. Class Access Specifiers 1) public – object of derived class can be treated as object of base class (not vice-versa) 2) protected – more restrictive than public, but allows derived classes to know details of parents 3) private – prevents objects of derived class from being treated as objects of base class.
  • 15. Inheritance vs. Access private: x protected: y public: z private: x protected: y public: z private: x protected: y public: z Base class members x is inaccessible private: y private: z x is inaccessible protected: y protected: z x is inaccessible protected: y public: z How inherited base class members appear in derived class private base class protecte d base class public base class
  • 16. Inheritance vs. Access private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); class Test : public Grade When Test class inherits from Grade class using public class access, it looks like this: private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); void setScore(float); float getScore(); char getLetter();
  • 17. Inheritance vs. Access private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using protected class access, it looks like this: private members: int numQuestions: float pointsEach; int numMissed; public members: Test(int, int); protected members: void setScore(float); float getScore(); float getLetter(); class Test : protected Grade
  • 18. Inheritance vs. Access private members: int numQuestions: float pointsEach; int numMissed; void setScore(float); float getScore(); float getLetter(); public members: Test(int, int); private members: char letter; float score; void calcGrade(); public members: void setScore(float); float getScore(); char getLetter(); class Grade private members: int numQuestions; float pointsEach; int numMissed; public members: Test(int, int); When Test class inherits from Grade class using private class access, it looks like this: class Test : private Grade
  • 19. Constructors and Destructors in Base and Derived Classes • Derived classes can have their own constructors and destructors • When an object of a derived class is created, the base class’s constructor is executed first, followed by the derived class’s constructor • When an object of a derived class is destroyed, its destructor is called first, then that of the base class
  • 20. Constructors and Destructors in Base and Derived Classes
  • 21. Constructors and Destructors in Base and Derived Classes
  • 22. Constructors and Destructors in Base and Derived Classes
  • 23. Passing Arguments to Base Class Constructor • Allows selection between multiple base class constructors • Specify arguments to base constructor on derived constructor heading: Square::Square(int side) : Rectangle(side, side) • Can also be done with inline constructors • Must be done if base class has no default constructor
  • 24. Passing Arguments to Base Class Constructor Square::Square(int side):Rectangle(side,side) derived class constructor base class constructor derived constructor parameter base constructor parameters
  • 25. Redefining Base Class Functions • Redefining function: function in a derived class that has the same name and parameter list as a function in the base class • Typically used to replace a function in base class with different actions in derived class
  • 26. Redefining Base Class Functions • Not the same as overloading – with overloading, parameter lists must be different • Objects of base class use base class version of function; objects of derived class use derived class version of function
  • 30. Problem with Redefining • Consider this situation: – Class BaseClass defines functions x() and y(). x() calls y(). – Class DerivedClass inherits from BaseClass and redefines function y(). – An object D of class DerivedClass is created and function x() is called. – When x() is called, which y() is used, the one defined in BaseClass or the the redefined one in DerivedClass?
  • 31. Problem with Redefining BaseClass DerivedClass void X(); void Y(); void Y(); DerivedClass D; D.X(); Object D invokes function X() In BaseClass. Function X() invokes function Y() in BaseClass, not function Y() in DerivedClass, because function calls are bound at compile time. This is static binding.
  • 32. Class Hierarchies • A base class can be derived from another base class.
  • 33. Class Hierarchies • Consider the GradedActivity, FinalExam, PassFailActivity, PassFailExam hierarchy in Chapter 15.
  • 34. Polymorphism and Virtual Member Functions • Virtual member function: function in base class that expects to be redefined in derived class • Function defined with key word virtual: virtual void Y() {...} • Supports dynamic binding: functions bound at run time to function that they call • Without virtual member functions, C++ uses static (compile time) binding
  • 35. Polymorphism and Virtual Member Functions Because the parameter in the displayGrade function is a GradedActivity reference variable, it can reference any object that is derived from GradedActivity. That means we can pass a GradedActivity object, a FinalExam object, a PassFailExam object, or any other object that is derived from GradedActivity. A problem occurs in Program 15-10 however...
  • 37. As you can see from the example output, the getLetterGrade member function returned ‘C’ instead of ‘P’. This is because the GradedActivity class’s getLetterGrade function was executed instead of the PassFailActivity class’s version of the function.
  • 38. Static Binding • Program 15-10 displays 'C' instead of 'P' because the call to the getLetterGrade function is statically bound (at compile time) with the GradedActivity class's version of the function. We can remedy this by making the function virtual.
  • 39. Virtual Functions • A virtual function is dynamically bound to calls at runtime. At runtime, C++ determines the type of object making the call, and binds the function to the appropriate version of the function.
  • 40. Virtual Functions • To make a function virtual, place the virtual key word before the return type in the base class's declaration: virtual char getLetterGrade() const; • The compiler will not bind the function to calls. Instead, the program will bind them at runtime.
  • 41. Updated Version of GradedActivity The function is now virtual. The function also becomes virtual in all derived classes automatically!
  • 42. Polymorphism If we recompile our program with the updated versions of the classes, we will get the right output, shown here: (See Program 15-11 in the book.) This type of behavior is known as polymorphism. The term polymorphism means the ability to take many forms. Program 15-12 demonstrates polymorphism by passing objects of the GradedActivity and PassFailExam classes to the displayGrade function.
  • 45. Polymorphism Requires References or Pointers • Polymorphic behavior is only possible when an object is referenced by a reference variable or a pointer, as demonstrated in the displayGrade function.
  • 46. Base Class Pointers • Can define a pointer to a base class object • Can assign it the address of a derived class object
  • 47. Base Class Pointers • Base class pointers and references only know about members of the base class – So, you can’t use a base class pointer to call a derived class function • Redefined functions in derived class will be ignored unless base class declares the function virtual
  • 48. Redefining vs. Overriding • In C++, redefined functions are statically bound and overridden functions are dynamically bound. So, a virtual function is overridden, and a non-virtual function is redefined.
  • 49. Virtual Destructors • It's a good idea to make destructors virtual if the class could ever become a base class. • Otherwise, the compiler will perform static binding on the destructor if the class ever is derived from. • See Program 15-14 for an example
  • 50. Abstract Base Classes and Pure Virtual Functions • Pure virtual function: a virtual member function that must be overridden in a derived class that has objects • Abstract base class contains at least one pure virtual function: virtual void Y() = 0; • The = 0 indicates a pure virtual function • Must have no function definition in the base class
  • 51. Abstract Base Classes and Pure Virtual Functions • Abstract base class: class that can have no objects. Serves as a basis for derived classes that may/will have objects • A class becomes an abstract base class when one or more of its member functions is a pure virtual function
  • 52. Multiple Inheritance • A derived class can have more than one base class • Each base class can have its own access specification in derived class's definition: class cube : public square, public rectSolid; class square class rectSolid class cube
  • 53. Multiple Inheritance • Problem: what if base classes have member variables/functions with the same name? • Solutions: – Derived class redefines the multiply-defined function – Derived class invokes member function in a particular base class using scope resolution operator :: • Compiler errors occur if derived class uses base class function without one of these solutions
  • 54. TEMPLATES AND FILE OPERATIONS Templates, Function templates, class Templates, Overloading of Template Functions Member function Templates, File stream operations- ostream,ifstream,fstream,File Access Modes File position pointer – fseek get,fseek put,ftell get, ftell put, Sequential Input and Output operations Random Access, Error handling during file operation.
  • 55. Templates in C++ • It is a simple and powerful tool in C++ • simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. • Templates are often used in larger codebase for the purpose of code reusability and flexibility of the programs. • The concept of templates can be used in two different ways: • Function Templates • Class Templates How it works? • Templates are expanded at compiler time. This is like macros. • Difference between Macro and Template is compiler does type checking before template expansion.
  • 56. Function Templates • A function template works in a similar to a normal function, with one key difference. • A single function template can work with different data types at once but, a single normal function can only work with one set of data types. • Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration. • However, a better approach would be to use function templates because you can perform the same task writing less and maintainable code.
  • 57. How to declare a function template? A function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration. template <typename T> T someFunction(T arg) { ... .. ... } • In the above code, T is a template argument that accepts different data types (int, float), and class is a keyword. • You can also use keyword typename instead of class in the above example. • When, an argument of a data type is passed to someFunction( ), compiler generates a new version of someFunction() for the given data type.
  • 59. Class Templates • Like function templates, you can also create class templates for generic class operations. • Sometimes, you need a class implementation that is same for all classes, only the data types used are different. • Normally, you would need to create a different class for each data type OR create different member variables and functions within a single class. • This will unnecessarily bloat your code base and will be hard to maintain, as a change is one class/function should be performed on all classes/functions. • However, class templates make it easy to reuse the same code for all data types.
  • 60. How to declare a class template? template <class T> class className { ... .. ... public: T var; T someOperation(T arg); ... .. ... }; • In the above declaration, T is the template argument which is a placeholder for the data type used. • Inside the class body, a member variable var and a member function someOperation() are both of type T.
  • 61. How to create a class template object? To create a class template object, you need to define the data type inside a < > when creation. className<dataType> classObject; For example: className<int> classObject; className<float> classObject; className<string> classObject;
  • 62. Overloading of Template Functions • You may overload a function template either by a non- template function or by another function template. • If you call the name of an overloaded function template, the compiler will try to deduce its template arguments and check its explicitly declared template arguments. If successful, it will instantiate a function template specialization, then add this specialization to the set of candidate functions used in overload resolution. • The compiler proceeds with overload resolution, choosing the most appropriate function from the set of candidate functions. Non-template functions take precedence over template
  • 63. Files - Introduction • Computer programs are associated to work with files as it helps in storing data & information permanently. • File - itself a bunch of bytes stored on some storage devices. • In C++ this is achieved through a component header file called fstream.h • The I/O library manages two aspects- as interface and for transfer of data. • The library predefine a set of operations for all file related handling through certain classes.
  • 64. File Handling using File Streams in C++ File represents storage medium for storing data or information. Streams refer to sequence of bytes. In Files we store data i.e. text or binary data permanently and use these data to read or write in the form of input output operations by transferring bytes of data. So we use the term File Streams/File handling. We use the header file <fstream> 1. 2. 3. ofstream: It represents output Stream and this is used for writing in files. ifstream: It represents input Stream and this is used for reading from files. fstream: It represents both output Stream and input Stream. So it can read from files and write to files. Operations in File Handling: Creating a file Reading data Writing new data Closing a file : open() : read() : write() : close()
  • 65. • Streams act as an interface between files and programs. • They represent as a sequence of bytes and deals with the flow of data. • Every stream is associated with a class having member functions and operations for a particular kind of data flow. • File -> Program ( Input stream) - reads • Program ->File (Output stream) – write • All designed into fstream.h and hence needs to be included in all file handling programs. • To use the fstream library, include both the standard <iostream> AND the <fstream> header file:
  • 67. Stream Classes for File Operations in C++
  • 69. C++ File Pointers Every file maintains two pointers called • get_pointer (in input mode file) • put_pointer (in output mode file) which tells the current position in the file where reading or writing will takes place respectively A file pointer in this context is not like a C++ pointer but it works like a book-mark in a book. These pointers help attain random access in file. That means moving directly to any location in the file instead of moving through it sequentially.
  • 70. Sequential Access Vs Random File Access Sequential Access Random Access In a sequential-access file, it is possible to read and write information sequentially, starting from the beginning of the file. A random-access data file enables you to read or writeinformation anywhere in the file. To go from point A to point Z in a sequential-access system, you must pass through all intervening points. In a random-access system, you can jump directly to point Z. Random access is sometimes called direct access. If information is accessed in the same order, a sequential-access file is faster. To access information randomly, random access is better
  • 71. Random Access Files There may be situations where random access in the best choice. For example, if you have to modify a value in record no 21, then using random access techniques, you can place the file pointer at the beginning of record 21 and then straight-way process the record. If sequential access is used, then you'll have to unnecessarily go through first twenty records in order to reach at record 21. The seekg(), seekp(), tellg() and tellp() Functions In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp() functions. The seekg() and tellg() functions allow you to set and examine the get_pointer, and the seekp() and tellp() functions perform these operations on the put_pointer. The seekg() and tellg() functions are for input streams (ifstream) and seekp() and tellp() functions are for output streams (ofstream).
  • 73. Error handling during file operation. Error handling refers to the response and recovery procedures from error conditions present in a software application. In other words, it is the process comprised of anticipation, detection and resolution of application errors, programming errors or communication errors. It is possible that an error may occur during I/O operations on a file. Typical error situations include: 1. Trying to read beyond the end-of-file mark. 2. Device overflow means no space in the disk for storing data. 3. Trying to use a file that has not been opened. 4. Trying to perform operation on a file, when the file is opened for another type of operation. 5. Opening a file with an invalid filename. 6. Try to read a file with no data in it. If we fail to check such read and write errors, a program may behave abnormally when an error occurs. An unchecked error may result in a premature termination of the program or incorrect output.
  • 74. Function Meaning int bad() Returns a non-zero value if an invalid operation is attempted or any unrecoverable error has occurred. However, if it is zero (false value), it may be possible to recover from any other error reported and continue operations. int eof() Returns non-zero (true value) if end-of-file is encountered while reading; otherwise returns zero (false value). int fail() Returns non-zero (true) when an input or output operation has failed. int good() Returns non-zero (true) if no error has occurred. This means, all the above functions are false. For example, if fin.good() is true, everything is okay with the stream named as fin and we can proceed to perform I/O operations. When it returns zero, no further operations can be carried out. clear() Resets the error state so that further operations can be attempted. Following table lists these error handling functions and their meaning :
  • 75. EXCEPTION HANDLING AND STL Exception handing mechanism, Throwing mechanism catching mechanism, Rethrowing an exception, C++ Standard Exception Library, runtime error, logic failures, user defined exceptions, Exception handling in inheritance, specifying exceptions. C++ standard STL.- Containers, Algorithms, Iterators – Standard function library
  • 76. Exception in Programs • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. • Many different kinds of errors can cause exceptions: problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. Exception in C++ • A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. • Exceptions provide a way to transfer control from one part of a program to another. • C++ exception handling is built upon three keywords: try, catch, and throw.
  • 77. Exception in C++ - Continued 1. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. 2. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. 3. try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. #include <stdexcept> // To use built in Exception Library try { // protected code } catch( ExceptionName e1 ) { // catch block } catch( ExceptionName e2 ) { // catch block } catch( ExceptionName eN ) { // catch block }
  • 78. C++ Standard Exceptions C++ provides a list of standard exceptions defined in <exception> which we can use in our programs. These are arranged in a parent- child class hierarchy shown below
  • 79. Exception Programs Runtime Errors & Logic Failures - Example • Divide by Zero Exception • Array Index Out of Bounds Exception • Overflow Error Assignment - 1 Write a calculator program in C++ with necessary exception handling mechanisms
  • 80. Throwing mechanism & Catching mechanism The exception handler is declared with the catch keyword immediately after the closing brace of the try block. The syntax for catch is similar to a regular function with one parameter. The type of this parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only in the case they match, the exception is caught by that handler. Multiple handlers (i.e., catch expressions) can be chained; each one with a different parameter type. Only the handler whose argument type matches the type of the exception specified in the throw statement is executed. If an ellipsis (...) is used as the parameter of catch, that handler will catch any exception no matter what the type of the exception thrown. This can be used as a default handler that catches all exceptions not caught by other handlers
  • 81. C++ User-Defined Exceptions The new exception can be defined by overriding and inheriting exception class functionality. #include <iostream> #include <exception> using namespace std; //Creating a user defined exception class class MyException : public exception{ public: const char * what() const throw() { return "Attempted to divide by zero!n"; } };
  • 82. Rethrowing an exception • Rethrowing an expression from within an exception handler can be done by calling throw, by itself, with no exception. • This causes current exception to be passed on to an outer try/catch sequence. • An exception can only be rethrown from within a catch block. • When an exception is rethrown, it is propagated outward to the next catch block. void MyHandler() { try { throw "Hello"; } catch (const char*) { cout <<"Caught exception inside MyHandlern"; throw; //rethrow char* out of function }
  • 83. Exception Handling in Inheritance Exception Handling – catching base and derived classes as exceptions: If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class. If we put base class first then the derived class catch block will never be reached. For example, following C++ code prints “Caught Base Exception” In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code.
  • 84. #include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; // some other stuff try { // Some monitored code throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { //This catch block is NEVER executed cout<<"Caught Derived Exception"; } getchar(); return 0; } In this C++ code, if we change the order of catch statements then both catch statements become reachable.
  • 85. Exception specifications (throw, noexcept) (C++) • Exception specifications are a C++ language feature that indicate the programmer's intent about the exception types that can be propagated by a function. • You can specify that a function may or may not exit by an exception by using an exception specification. • The compiler can use this information to optimize calls to the function, and to terminate the program if an unexpected exception escapes the function. • If exception handling is used in an application, there must be a function in the call stack that handles thrown exceptions before they exit the outer scope of a function marked noexcept, noexcept(true), or throw() • Syntax void MyFunction(int i) throw(); void MyFunction(int i) noexcept;
  • 86. Assignment / Lab Excercise Write a program that converts dates from numerical month/day format to alphabetic month/day (for example, 1/31 or 01/31 corresponds to January 31). You will define two exception classes, one called MonthErrorand another called DayError. If the user enters anything other than a legal month number (integers from 1 to 12), then your program will throw and catch a MonthError. Similarly, if the user enters anything other than a valid day number (integers from 1 to either 29, 30, or 31, depending on the month), then your program will throw and catch a DayError. To keep things simple, always allow 29 days for February.
  • 88. Introduction to the Standard Template Library The Standard Template Library, or STL, is a C++ library of container classes, algorithms, and iterators; it provides many of the basic algorithms and data structures of computer science. The STL is a generic library, meaning that its components are heavily parameterized: almost every component in the STL is a template. You should make sure that you understand how templates work in C++ before you use the STL. The STL includes the classes vector, list, deque, set, multiset, map, multimap, hash_set, hash_multiset, hash_map, and hash_multimap. Each of these classes is a template, and can be instantiated to contain any type of object
  • 89. STL has four components 1. Algorithms 2. Containers 3. Functions 4. Iterators
  • 90. Algorithms The header algorithm defines a collection of functions especially designed to be used on ranges of elements.They act on containers and provide means for various operations for the contents of the containers. Algorithm Sorting Searching Important STL Algorithms Useful Array algorithms Partition Operations Containers Containers or container classes store objects and data. There are in total seven standard “first-class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors. Refer to types of containers in slide 16 Functions The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed.
  • 91. Vector in C++ STL • Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. • Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. • Inserting at the end takes differential time, as sometimes there may be a need of extending the array. • Removing the last element takes only constant time because no resizing happens. • Inserting and erasing at the beginning or in the middle is linear in time.
  • 92. Vector in C++ STL Certain functions associated with the vector are: Iterators • begin() – Returns an iterator pointing to the first element in the vector • end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector • rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element • rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end) • cbegin() – Returns a constant iterator pointing to the first element in the vector. • cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector. • crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element • crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end)
  • 93. List in C++ STL Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions. List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it. They are very similar to forward_list: The main difference being that forward_list objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient. Compared to other base standard sequence containers (array, vector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.
  • 94. List in C++ - Sequence Containers Some more useful functions are discussed in this article 1. emplace(position, value) :- This function is used to insert an element at the position specified. 2. emplace_back(value) :- This function adds value at end of list. 3. emplace_front :- This function adds value at beginning of list 4. merge(list2) :- This function is used to merge list2 with list1. If both the lists are in sorted order, then the resulting list is also sorted. 5. remove_if(condition) :- This function removes the element from list on the basis of condition given in its argument 6. unique() :- This function is used to delete the repeated occurrences of the number. List has to be sorted for this function to get executed. 7. splice(position, list2) :- This function is used to transfer elements from one list into another. 8. swap(list2) :- This function is used to swap one list element with other.
  • 95. Set in C++ STL • Sets are containers that store unique elements following a specific order. In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container. • Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare). • Set containers are generally slower than unordered_set containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order. • Sets are typically implemented as binary search trees.
  • 96. Set in C++ STL Some basic functions associated with Set: • begin() – Returns an iterator to the first element in the set. • end() – Returns an iterator to the theoretical element that follows last element in the set. • size() – Returns the number of elements in the set. • max_size() – Returns the maximum number of elements that the set can hold. • empty() – Returns whether the set is empty. • count(const g) – Returns 1 or 0 based on the element ‘g’ is present in the set or not. • lower_bound(const g) – Returns an iterator to the first element that is equivalent to ‘g’ or definitely will not go before the element ‘g’ in the set. • upper_bound(const g) – Returns an iterator to the first element that is equivalent to ‘g’ or definitely will go after the element ‘g’ in the set. • equal_range()– The function returns an iterator of pairs. (key_comp). The pair refers to the range that includes all the elements in the container which have a key equivalent to k. • emplace()– This function is used to insert a new element into the set container, only if the element to be inserted is unique and does not already exists in the set.
  翻译: