Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views121 pages

OOPs Using C++ Notes

This document outlines a syllabus for a course on Object Oriented Programming (OOP) using C++. It covers various modules including an introduction to C++, control structures, classes, inheritance, and exception handling, along with prerequisites and course materials. Key concepts of OOP such as encapsulation, abstraction, polymorphism, and inheritance are also discussed in detail.

Uploaded by

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

OOPs Using C++ Notes

This document outlines a syllabus for a course on Object Oriented Programming (OOP) using C++. It covers various modules including an introduction to C++, control structures, classes, inheritance, and exception handling, along with prerequisites and course materials. Key concepts of OOP such as encapsulation, abstraction, polymorphism, and inheritance are also discussed in detail.

Uploaded by

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

Object

Oriented
Programming
(OOP)
Syllabus
Module 1
Introduction to C++: Object Oriented Technology, Advantages of OOP, Input-output in C++, Tokens, Keywords,
Identifiers, Data Types C++, Derives data types. The void data type, Type Modifiers, Typecasting, Constant,
Operator, Precedence of Operators, Strings.
Module 2
Control Structures and Functions: Decision making statements like if-else, Nested if-else, goto, break, continue,
switch case, Loop statement like for loop, nested for loop, while loop, do-while loop. Parts of Function, User-
defined Functions, Value- Returning Functions, void Functions, Value Parameters, Function overloading, Virtual
Functions.
Module 3
Classes and Data Abstraction: Structure in C++, Class, Build-in Operations on Classes, Assignment Operator and
Classes, Class Scope, Reference parameters and Class Objects (Variables), Member functions, Accessor and
Mutator Functions, Constructors, default Constructor, Destructors.
Module 4
Overloading, Templates and Inheritance: Operator Overloading, Function Overloading, Function Templates,
Class Templates. Single and Multiple Inheritance, virtual Base class, Abstract Class, Pointer and Inheritance,
Overloading Member Function.
Module 5
Pointers, Arrays and Exception Handling: Void Pointers, Pointer to Class, Pointer to Object, Void Pointer, Arrays.
The keywords try, throw and catch. Creating own Exception Classes, Exception Handling Techniques (Terminate
the Program, Fix the Error and Continue, Log the Error and Continue), Stack Unwinding.
Prerequisites
• C++ basic
• Input output
• Data types
• Structure
• Function
• declaration
• definition
• Calling
In This Course
• Notes pdf
• Theory + Practical
• Theory on Board
• Practical on laptop
Let’s start
• C++
• C++ was developed by Bjarne Stroustrup
• Extension to the C language.
• C++ gives programmers a high level of control over system resources
and memory.
Introduction Of OOP
Procedural Oriented Programming :-
• Procedural programming is a programming paradigm that focuses on
procedures or functions that perform specific tasks. It is a step-by-step
approach to programming, where the program is divided into smaller
procedures or functions, each with its own specific task
• Function is a prime focus and very little attention was given to data that
are be used by function
• For every long program it is very difficult to track that what data is used by
which function
• Data movement is open
• Function modifier data from one form to another form
C structure Vs C++ structure
C structure C ++ structure

Collection of variable Collection of variable

Member are public Member are public & privet


by default public
Object Oriented Programming in C++ :-
• As the name suggests uses objects in programming.
• The main aim of OOP is to bind together the data and the functions
that operate on them so that no other part of the code can access
this data except that function.
• Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc. in programming.
Characteristics of OOP :-
• Data is critical
• Does not allow data to move freely around the system
• Data & function are more tightly bound
• Protect data from accidental modification by function outside
• Decomposition of problem into objects
• Data of an object can be access by the function associated with it and
function of one object can asses the function of other object
Concepts Of OOPs :-
1.Class
2.Objects
3.Encapsulation
4.Abstraction
5.Polymorphism
6.Inheritance
7.Dynamic Binding
8.Message Passing
Class & object
Class :-
✓Class is user define data type declared with using keyword “class” , and
it is collection of member variable and member function, class member
is operate by three access specifiers private, protected and pubic.
✓By default its member is private

Syntax of class :-
class class_name
{
data;
Fun( );
};
Some points about Class

• Extension of structure
• Logical entity / blueprint (space not occupy). (Object physical space occupy)
• No actual memory holding
• One class can have as many object as it needed
• Class acts as a data type for its object
• Class is a collection of objects of similar type
Example
Object :-
• An object is an instance of a class . It represent a specific entity or thing
that is created based on the blueprint provided by the class
Some points about object
• Object is a real world entity
• Object has a state and behaviour
• Object state is a set of property value of particular instant
• Object physical space occupy
cin >> extraction operator
cout << insertion operator

To access of public member of class using .(dot)

:: scope resolution
Example
C++ structure Vs C++ class
C++ structure C++ class
User define User defined
Collection of variable and function Collection of variable and function
Member public or private Member public or private
By default public By default private

Not inheritance inheritance


Access Modifiers
Access Modifiers

• Access Modifiers (Access Specifiers) are keywords that are


used in OOP (object-oriented programming) in order to
specify the accessibility of the methods, classes,
constructors, and other members of the class.

• Access modifiers are used to implement an important aspect


of Object-Oriented Programming known as Data Hiding.
Data hiding :-
• Data hiding is an object-oriented programming technique for
protecting the data within a class from unwanted access and
preventing unneeded intrusion from outside the class.
• It helps hide internal object details, i.e., data members
within the class, to prevent its direct access from outside the
class.
There are 3 types of access modifiers
1.Public
2.Private
3.Protected

• Note: If we do not specify any access modifiers for the members


inside the class, then by default the access modifier for the members
will be Private.
Public:
• All the class members declared under the public specifier will be
available to everyone.
• The data members and member functions declared as public can be
accessed by other classes and functions too.
• The public members of a class can be accessed from anywhere in the
program using the direct member access operator (.) with the object
of that class.
Example
Private:
• The class members declared as private can be accessed only by the
member functions inside the class.
• They are not allowed to be accessed directly by any object or function
outside the class.
• Only the member functions or the friend functions are allowed to
access the private data members of the class.
Example
Protected:
• The protected access modifier is similar to the private access modifier
in the sense that it can’t be accessed outside of its class unless with
the help of a friend class.
• The difference is that the class members declared as Protected can be
accessed by any subclass (derived class) of that class as well.

• Note: This access through inheritance can alter the access modifier of
the elements of base class in derived class depending on the mode of
Inheritance.
Example
Friend function
• Friend function is a non member function of the class which have
access to the private member of that class
• It is not in the scope of the class to the class to which it has be declare
as friend so it cant be called using the object of that class
• It can be called like a normal function
• It can’t the access the member by name directly but it has to use an
object name and dot membership operator with each member name
• It can be declare either in public or private section of a class without
affecting its meaning
• Usually friend function takes object as an argument
Advantages of Friend Function
• The friend function allows the programmer to generate more efficient
codes.
• It allows the sharing of private class information by a non-member
function.
• It accesses the non-public members of a class easily.
• It is widely used in cases when two or more classes contain the
interrelated members relative to other parts of the program.
• It allows additional functionality that is not used by the class
commonly.
Constructor & destructor
Constructor
• Constructor is a special member function used to initialized the object at time of
its creation
• They should be declared in public section
• Constructor is called automatically when object are created
• Do not have return type
• They can not be inherited but a derived class constructor can call the base class
constructor
• They have default argument
• Constructor can not be virtual
• When constructor is declared for a class then initialization of the class object
becomes mandatory
• Constructor name is class name
There are three type of constructor

1. No argument constructor or default constructor


2. Parameterize constructor
3. Copy constructor
Default constructor

✓ constructor without any arguments or with the default value for every
argument is said to be the Default constructor.
✓ A constructor that has zero parameter list or in other sense, a constructor that
accepts no arguments is called a zero-argument constructor or default
constructor.

If programmer do not supply or provide any constructor then a


default constructor supply by the compiler
Parameterize constructor
✓ constructors that accept parameters.
✓ They enable programmers to create objects with specific
properties and attributes by passing arguments.
✓ Multiple parameterized constructors can be defined in a class,
offering flexibility in object initialization.
• The parameter of a constructor can be of any type except that of the
class to which it belongs
• But constructor can except a reference to its own class
• Constructor can take default argument
Copy constructor
• A copy constructor takes an reference to an object of same class as its
self as an argument

• It copy data item of one object to another object

✓ copy constructor needed when the class has one or more data
members that are pointers or references. Also, when the class has
dynamically allocated memory.
Destructor
• A destructor is use to destroy objects that have been created by a constructor
• Destructor is also a member function whose name is same as class name but is
preceded by a tilde (~) symbol
• Destructor is called automatically when object goes out of scope that means
when function end, program end, or a block can containing local variable ends
• Only one destructor is possible in a class
• Destructor takes no argument and it also not have any return type
• If programmer do not supply destructor in a class then compiler created
default destructor
• When a class contain a pointer to memory allocated in class we should write a
destructor to release memory before the class instance ( object) is destroyed
by doing this we can avoid memory leak
Static variable & Static member function
• Static variable are use to maintain values common to the entire class
• Static variable are initialize to zero when 1st object of its class is created
• Only one copy of static variable created for entire class
• It is visible only within the class but its life time is the entire program
• Static member must be define outside the class
• Static member are also known as class variable
• Only one copy of static variable shared with all object
• Static member function can have access to only other static members
(variable & function)
• Can we called using class name ( class_name :: fun )
Encapsulation
• Encapsulation defined as the
wrapping up of data and information
in a single unit.
• Encapsulation is defined as binding
together the data and the functions
that manipulate them.
Two Important property of Encapsulation
1. Data Protection :- Encapsulation protects the internal state of an
object by keeping its data members private. Access to and modification
of these data members is restricted to the class’s public methods,
ensuring controlled and secure data manipulation.

2. Information Hiding :- Encapsulation hides the internal implementation


details of a class from external code. Only the public interface of the
class is accessible, providing abstraction and simplifying the usage of
the class while allowing the internal implementation to be modified
without impacting external code.
Features of Encapsulation
1.We can not access any function from the class directly. We need an
object to access that function that is using the member variables of
that class.
2.The function which we are making inside the class must use only
member variables, only then it is called encapsulation.
3.If we don’t make a function inside the class which is using the
member variable of the class then we don’t call it encapsulation.
4.Encapsulation improves readability, maintainability, and security by
grouping data and methods together.
5.It helps to control the modification of our data members.
Abstraction
• Data abstraction is one of the most essential and important features
of object-oriented programming .
• Abstraction means displaying only essential information and hiding
the details.
• Data abstraction refers to providing only essential information about
the data to the outside world, hiding the background details or
implementation.
Types of Abstraction:
1. Data abstraction – This type only shows the required information
about the data and hides the unnecessary data.
2. Control Abstraction – This type only shows the required
information about the implementation and hides unnecessary
information.
Binding
• Association of a function definition to a function call or association of
a value to a variable is called binding

➢Static binding / compile time binding / early binding :- function will


be invoked or what value allotted to a variable at compile time

➢Dynamic binding / run time binding / later binding :- function will be


invoked or what value allotted to a variable at run time
Static binding Dynamic / run
Occur at compile time Occur at run time
Efficiency high Efficiency Low
Flexibility low Flexibility high
Execution fast Execution Slow(comparably)
E.g. fun overloading E.g. virtual function(C++)
Operator overloading Function overriding(java)
Polymorphism
✓ The word “polymorphism” means having many forms. In simple
words, we can define polymorphism as the ability of a message to be
displayed in more than one form.

• Polymorphism is a ability to exhibit different behaviour in different


instances
• Behaviour of an operation depends on the type of data used in
operation
Polymorphism

Run time Compile time

Virtual function Function Operator


overloading overloading
Function overloading :-
✓same function name can be used to handle different number and
different type of argument
e.g.
void fun (int , int);
void fun (int , float);
void fun (float , float);
Operator overloading
• Operator overloading provides mechanism to give special meaning to
an operator show that they can behave in same way for derived data
type as they behave for built in data type

• Syntax
return_type class_name :: operator operator_symbol (argument_list)
{
//body
} keyword
• Operator overloading does not change the of an operator
• Semantics of an operator can be extended but can’t change its syntax, the grammatical
rule such as number of operands, precedence & associativity
• Operator overloading achieve through a special function called operator function
• Operator function must be either member function (non static) or friend function
• Member function will have no argument for unary operator but have single argument for
binary operator
• This is because object invoking member function passed implicitly to the member
function ( through this pointer )
• Friend function will have one argument for unary operator & two for binary operator
because friend are non member function show this point is not available for it
➢Friend function is used to overload binary operator where left hand
operand of built in data type and right hand operand is object
➢Some of operator that can have not overload
• sizeof()
• Membership operator .
• Pointer to member . *
• Scope resolution ::
• Conditional ? :

➢List of operator which is not overloaded by friend function


• Assignment operator =
• Function call ()
• Subscripting []
• Classmember access →
Inheritance
Inheritance OR Derivation
• The mechanism of driving a new class from an old one or existing
class is called inheritance
• The derived class inherits some or all of the feature of the base class
• The new class created is called “derived class” or “child class” and the
existing class is known as the “base class” or “parent class”.
• Sub Class: The class that inherits properties from another class is
called Subclass or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is
called Base Class or Superclass.
Why and when to use inheritance?
Syntax

class derived_class_name : access-specifier base_class_name


{
//body
}
Modes of Inheritance:

1. Public Mode: If we derive a subclass from a public base class. Then


the public member of the base class will become public in the
derived class and protected members of the base class will become
protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class.
Then both public members and protected members of the base class
will become protected in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then
both public members and protected members of the base class will
become Private in the derived class.
Types of inheritance

1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Single inheritance
• In single inheritance, a class is
allowed to inherit from only
one class. i.e. one subclass is
inherited by one base class
only.
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
Multiple inheritance

• Multiple Inheritance is a feature of C++ where a class can inherit from


more than one class. i.e one subclass is inherited from more than one
base class.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
// body of subclass
}; class B
{
... .. ...
};
class C
{
... .. ...
};
class A: public B, public C
{
... ... ...
};
Multi level inheritance
• In this type of inheritance, a
derived class is created from
another derived class.
Syntax: class C
{
... .. ...
};
class B:public C
{
... .. ...
};
class A: public B
{
... ... ...
};
Hierarchical inheritance
• In this type of inheritance, more than one subclass is inherited from a
single base class. i.e. more than one derived class is created from a single
base class.
Syntax: class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Hybrid (Virtual) Inheritance:
• Hybrid Inheritance is implemented by combining more than one type of
inheritance.
• For example: Combining Hierarchical inheritance and Multiple
Inheritance.
Diamond Problem

• The Diamond Problem is an ambiguity


error that arises in multiple inheritance
when a derived class inherits from two or
more base classes that share a common
ancestor. This results in the inheritance
hierarchy forming a diamond shape, hence
the name “Diamond Problem.”

• The ambiguity arises because the derived


class has multiple paths to access
members or methods inherited from the
common ancestor, leading to confusion
during method resolution and member
access.
Virtual base class
• Child inherits the property of grand parent via two different paths
• All the public & protected member of grand parent are inherited into
child twice via two different paths so child would have duplicate set
of member inherited from grand parent
• To avoid this empirgotic we should make common base class as
virtual base class while declaring the direct or intermediate base
classes
Constructor in derive class
• When there are no parameterize constructor in base class the derived
class need not have a constructor other wise it is mandatory for the
derived class to have a constructor and pass the argument to the base
class constructor
• Base class constructor executed first and then the constructor in the
derived class is executed
• In case of multi-level inheritance the constructor will be executed in order
of inheritance
• In case of multiple inheritance base class constructor are called in the
order in which they appear in the declaration of derived class
• The constructor for virtual base classes are invoked before any non virtual
base classes
• The constructor of the derived class receives the entire list of values as its
argument and passes them on to the base constructor in the order in
which they are declare in the derived class
• The base constructor are called and executed before executing the
statements in the body of derived constructor

Syntax
Derived_class_constructor ( arg_list1,arg_list2,……arg_listN, Arg_list_D) : base_1(arg_list1),base_2(arg_list2)…..
{
//body of derived class constructor

}
Pointer to derived class
• Pointer to object of a base class are type compatible with pointer to object of a
derived class so base class pointer can be used to point the to the derived class
object
• Base class pointer can point to a derived class object but while accessing the
public member of derive classes be have to careful because through base class
pointer we can access only those member which are inherited from base class
and not the member that are originally belong to derived class
When member of derive class has the some name as one of the member of base
class then any reference to that member by base class pointer will always access
base class member
So, in this case for accessing the member of derived class we have to typecast the
base type pointer into the derived type
((derived*)bptr)
• Base class pointer even when it is made to contain the address of a
derived class always executes the function in the base class because
the compiler simply ignore the contains of the pointer and choose the
member that matches the type pointer
Virtual function
• Virtual function is a member function that is declared within the base
class and can be redefined by the derived class.
• Virtual is a keyword
• When fun is made virtual, C++ determines which function to use at
runtime based on the type of object pointed to by the base pointer ,
rather than the type of the pointer thus by the making of base pointer
to point different object it is possible to executes different version of
the virtual function and hence achieving run time polymorphism
• Run time polymorphism is achieve only when a virtual function is
accessed through base pointer
Rule for virtual function
• Virtual function must be member of some class
• Virtual function can not be static
• Virtual function can be friend of another class
• Virtual function in base class must be defined even through it may not be used
• We can not have virtual constructor but we can have virtual destructor
• When a base pointer points to derived class incrementing or decrementing it
will not make it to point to the next object of derived class
• It is incrementing and decrementing only relative to its base class
Abstract class
• A class which is not used to create object is called abstract class
• Abstract class design only to act as a base class
• Class containing pure virtual function can’t be used to declare any
object of its own such type of class are called abstract base class
Interfaces
• Interfaces are nothing but a way to describe the behavior of a class
without committing to the implementation of the class.
• In C++ programming there is no built-in concept of interfaces.
• In order to create an interface, we need to create an abstract class
which is having only pure virtual methods.
• In C++, Interfaces are also called pure abstract classes.
Pure virtual function
• A pure virtual function is a virtual function that has no definition
within the class.
• A pure virtual function is a function declared in the base class that has
no definition related to the base class
• Virtual void show()=0;
• In this case the compiler requires each derived class to either defined
the function or redeclared it as a pure virtual function
• Class containing pure virtual function can’t be used to declare any
object of its own such type of class are called abstract base class
Exception Handling
• What is Exception :- An exception is an unexpected problem that arises
during the execution of a program , our program terminates suddenly
with some errors/issues. Exception occurs during the running of the
program (runtime).

• exceptions are runtime anomalies or abnormal conditions that a


program encounters during its execution. The process of handling these
exceptions is called exception handling.
• Using the exception handling mechanism, the control from one part of
the program where the exception occurred can be transferred to
another part of the code.
• Exception handling was not a part of original C++, it was new feature
added by ANSI (American National Standards Institute)
Types of C++ Exception
• There are two types of exceptions in C++
1.Synchronous: Exceptions that happen when something goes wrong
because of a mistake in the input data or when the program is not
equipped to handle the current type of data it’s working with, such as
dividing a number by zero.
2.Asynchronous: Exceptions that are beyond the program’s control,
such as disc failure, keyboard interrupts, etc.
C++ try and catch
C++ provides an inbuilt feature for Exception Handling.
It can be done using the following specialized keywords:
try, catch, and throw with each having a different purpose.
❖ Syntax of try-catch
try
{
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 )
{
// catch block catches the exception that is thrown from try block
}
✓try
The try keyword represents a block of code that may throw an exception placed inside the try block.
It’s followed by one or more catch blocks.
If an exception occurs, try block throws that exception.

✓catch
The catch statement represents a block of code that is executed when a particular exception is thrown
from the try block.
The code to handle the exception is written inside the catch block.

✓ throw
An exception thrown using the throw keyword.
When a program encounters a throw statement, then it immediately terminates the current function and
starts finding a matching catch block to handle the thrown exception.

Note: Multiple catch statements can be used to catch different type of exceptions thrown by try block.
The try and catch keywords come in pairs:
We use the try block to test some code and If the code throws an exception we will handle it in our
catch block.
Advantages
•Improved Error Handling: Exception handling in C++ provides a clean and efficient way
to handle runtime errors in a program. It separates error-handling code from normal code,
making the code cleaner and easier to maintain.
•Better Program Structure: Exception handling helps to improve the structure of a
program by allowing developers to separate error-handling code from the main logic of the
program. This makes the code more readable and easier to understand.
•Reduced Complexity: Exception handling can reduce the complexity of a program by
providing a unified mechanism for handling different types of errors. This allows developers to
write simpler and more maintainable code.
•Enhanced Performance: Exception handling can enhance the performance of a program
by providing a fast and efficient way to handle errors. It is faster than using traditional error-
handling methods, such as error codes, which can slow down a program’s execution.
•Increased Flexibility: Exception handling in C++ provides increased flexibility by allowing
developers to define their own exceptions and custom error-handling routines. This allows
developers to tailor the error-handling mechanism to the specific needs of their program.
Thank You!!

You might also like