0% found this document useful (0 votes)
60 views34 pages

Unit 2 (Oops)

Btech cse oops notes

Uploaded by

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

Unit 2 (Oops)

Btech cse oops notes

Uploaded by

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

UNIT-2(Features of object oriented programming)

Encapsulation- encapsulation in C++ is defined as the wrapping up of data and information in


a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the
data and the functions that manipulate them.

Consider a real-life example of encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. Now,

 The finance section handles all the financial transactions and keeps records of all the data
related to finance.

 Similarly, the sales section handles all the sales-related activities and keeps records of all
the sales.

Now there may arise a situation when for some reason an


official from the finance section needs all the data about sales
in a particular month.
In this case, he is not allowed to directly access the data of
the sales section. He will first have to contact some other
officer in the sales section and then request him to give the
particular data.
This is what Encapsulation is. Here the data of the sales
section and the employees that can manipulate them are
wrapped under a single name “sales section”.
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 o f the class while allowing the internal implementation to be modified
without impacting external code.

For example-Program to demonstrate encapsulation

Output- 5

Object identity
Object identity is a property of data that is created in the context of an object data model,
where an object is assigned a unique internal object identifier, or oid. The object identifier is
used to define associations between objects and to support retrieval and comparison of
object-oriented data based on the internal identifier rather than the attribute values of an
object.

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. A real-life
example of polymorphism is a person who at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So the
same person exhibits different behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and changing the
type of arguments. In simple terms, it is a feature of object-oriented programming
providing many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name. There are certain Rules of Function
Overloading that should be followed while overloading a function.
C++ program to show function overloading or compile-time polymorphism:
B. Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can make use of the addition
operator (+) for string class to concatenate two strings. We know that the task of this
operator is to add two operands. So a single operator ‘+’, when placed between integer
operands, adds them and when placed between string operands, concatenates them.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The
function call is resolved at runtime in runtime polymorphism. In contrast, with
compile time polymorphism, the compiler determines which function call to
bind to the object after deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be
overridden.

Runtime Polymorphism with Data Members


Runtime Polymorphism cannot be achieved by data members in C++. Let’s see
an example where we are accessing the field by reference variable of parent
class which refers to the instance of the derived class.
 Inheritance in C++
The capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important features of
Object Oriented Programming in C++.

where,
 class: keyword to create a new class
 derived_class_name: name of the new class, which will inherit the base
class
 access-specifier: Specifies the access mode which can be either of
private, public or protected. If neither is specified, private is taken as
default.
 base-class-name: name of the base class.
Example : Program to Demonstrate the Simple
Inheritance of a Class
Types Of Inheritance in C++
The inheritance can be classified on the basis of the relationship between the
derived class and the base class. In C++, we have 5 types of inheritances:
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1. Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one
base class is inherited by one derived class only.
2. 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
3. Multilevel Inheritance
In this type of inheritance, a derived class is created from another derived class
and that derived class can be derived from a base class or any other derived
class. There can be any number of levels.
4. 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.
5. Hybrid Inheritance
Hybrid Inheritance is implemented by combining more than one type of
inheritance. For example: Combining Hierarchical inheritance and Multiple
Inheritance will create hybrid inheritance in C++
There is no particular syntax of hybrid inheritance. We can just combine two of
the above inheritance types.
Example:
Below image shows one of the combinations of hierarchical and multiple
inheritances:
Class in C++
A class is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A C++ class
is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels, speed
limits, and mileage are their properties.
 A Class is a user-defined data type that has data members and member functions.
 Data members are the data variables and member functions are the functions used
to manipulate these variables together, these data members and member functions
define the properties and behaviour of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage, etc,
and member functions can be applying brakes, increasing speed, etc.
But we cannot use the class as it is. We first have to create an object of the class to use
its features. An Object is an instance of a Class.
syntax:
Object in C++
When a class is defined, only the specification for the object is defined; no memory or
storage is allocated. To use the data and access functions defined in the class, you need to
create objects.
Syntax to Create an Object
We can create an object of the given class in the same way we declare the variables of any
other inbuilt data type.

Accessing Data Members and Member Functions


The data members and member functions of the class can be accessed using
the dot(‘.’) operator with the object. For example, if the name of the object
is obj and you want to access the member function with the
name printName() then you will have to write:
Variables in c++
Variables in C++ is a name given to a memory location. It is the basic unit of storage in a
program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.
How to Declare Variables?

 Type Checking /Strict Type Checking in C++


Strict type checking means the function prototype(function signature) must be known for
each function that is called and the called function must match the function prototype. It is
done at compile time. The “strictly typed language” refers to a very strongly typed language
in which there are more strict restrictions as to how operations can be performed on
variables of different types.
Basic Terms:
 for each operation: The number, order, and data types of its arguments.
 for each variable: Name and datatype of each object.
 for each constant: Name, datatype, and value.

Generally, a strongly typed language has stricter typing rules


at compile-time, which implies that errors and exceptions are
more likely to happen during compilation, which increases the
reliability of the delivered program, “the compiler generates
errors if types don’t match up”.
The function prototype specifies the function
name and number of arguments passed and the return
type ( if any) of the function.
For Example:
Exceptions
Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such
as the name and description of the exception and the state of the program
when the exception occurred.
Major reasons why an exception Occurs
 Invalid user input
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Out of bound
 Null reference
 Type mismatch
 Opening an unavailable file
 Database errors
 Arithmetic errors

Errors represent irrecoverable conditions such as Java virtual machine (JVM)


running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of
the programmer, and we should not try to handle errors.
Difference between Error and Exception
 Error: An Error indicates a serious problem that a reasonable application
should not try to catch.
 Exception: Exception indicates conditions that a reasonable application
might try to catch.
Exception Hierarchy
All exception and error types are subclasses of the
class Throwable, which is the base class of the hierarchy. One
branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM)
to indicate errors having to do with the run-time environment
itself(JRE). StackOverflowError is an example of such an error.

Types of Exceptions

Exceptions can be categorized in two ways:


1. Built-in Exceptions

 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.
 Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by the
compiler.

 Unchecked Exceptions: The unchecked exceptions are just opposite to


the checked exceptions. The compiler will not check these exceptions at
compile time. In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it, the program would
not give a compilation error.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to
describe a certain situation. In such cases, users can also
create exceptions, which are called ‘user-defined Exceptions’.
 Templates
A template is a simple yet very powerful tool in C++. The
simple idea is to pass the data type as a parameter so that we
don’t need to write the same code for different data types.

Types of templates-2
a) Function Templates
b) Class Templates
a) Function templates:We write a generic function that can be used for
different data types.
Ex-sort(),max(),min(),printArray().
program
#include<iostream>
using namespace std;
template <class T>
T add(T a,T b)
{
cout<<"Addition="<<a+b;
}
main()
{
add(4.2,7.3);
}
Output
11.5
11.5

Class templates: A class template starts with the keyword template followed by
template parameter(s) inside <> which is followed by the class declaration.
Syntax
template <class T>
class className {
private:
T var;
... .. ...
public:
T functionName(T arg);
... .. ...
};
Program
#include<iostream>
using namespace std;
template <class T>
class CT
{
private:
T num1,num2;
public:
CT(T n1,T n2)
{
num1=n1;
num2=n2;
}
void check()
{
if(num1>num2)
{
cout<<num1<<" is the largest number\n";
}else{
cout<<num2<<" is the largest number";
}
}
};
int main()
{
CT c(5,8);
c.check();
return 0;
}

Memory management
Whenever a program is run some memory is allocated to that program.This
memory logically has 4 sections-
1) Stack
2) Heap
3) Data
4) Instructions

Stack:whenever we create a variable by SMA,these variables get


memory in stack.in stack,not only these variables get memory but also
other elements of a program grt memory.Local variables also get
memory in stack It means whenever a function is called,its variables get
memory in stack.When this function is end,memory of its variables get
released.Again a new function is called its variables get memory and
when this function is end memory of variables get released and so on.In
this way memory get increased or decreased.
In this,memory is allocated continuously.In this we can’t make free
memory of SMA variables.
Heap: whenever we create a variable by DMA,these variables get
memory in heap.
In this,memory is allocated randomly(not in an order).This happens
because in this section we can free memory from somewhere in
between by using free(),delete().
Data:usually global variables get memory in data.
 Total programs memory is divided in 2 parts-
 Consumed memory blocks
 Free memory blocks:whwnever malloc(),calloc(),new runs it
occupies some memory from free memory blocks.If all the free
memory is occupied after that you run malloc(),calloc(),new then
program will show memory error “not enough memory”.In this
situation program can crash.This is the situation which
programmer don’t want to be occurred.It means we have limited
memory.How complex is the program,we have to run in this
limited memory which id allocated to our program. That’s why we
need memory management.

 Here comes the concept of memory leak
memory leak:whenever we create a memory dynamically,a pointer will
point this block.

for example-we have a pointer *p(statically created in stack) which


points a memory block(dynamically created) in heap.
Because pointer is a variable of SMA as soon as its scope ends it will be
destroyed.If *p is destroyed then no one will point to memory
dynamically created.Dynamically created variable also doesn’t have
name only have address.That pointer(which has been destroyed) had Its
address.Now we cant access this memory block because it can only be
accessed with that address.
This memory block will be counted in consumed area.so it cant be
allocated to some other variable.Also this is not the free area.This
memory block is called memory leak.A programmer will make free this
memory by free() function.

Tools to mamage memory


In c/c++ memory management is done by the programmer but in
java,python,java script memory management is done automatically.We know
that when we create a program then we store the data in some
variables.Variables life exists till the program’s life.Variables exist during the
execution of a program.
Variables can be created by 2 ways/ Memory can be managed in two ways-
 SMA(Static memory allocation)/ Compile time memory allocation
 DMA(Dynamic memory allocation)/Run time memory allocation
1. SMA-In this, we create variables by declaring them first.
Ex- int x;
Int y[5];
int *p;
struct student s1;
The characterstics of these variables are decided at compile time.Like the
name of variable,when it will be formed,when it will be destroyed,which
type of vales it can store,how much memory size will be allotted to
it.These types of the variables are created when a programmer knows
the requirement(how much variables are needed) before starting of the
program.
1. DMA- These variables don’t have names,they only have address
when they are created.These variables can be accessed only
through pointers.
Sometimes we don’t know how many variables needed in the program.
for ex- we are making a program of calculating average of some numbers
entered by the user.How much numbers a user will enter,we don’t know.
In this case,when we don’t know the “no. of variables”,”size of array”
then we need to create variables dynamically.
# When we know that user will enter a fix no. of values then use
SMA.
# When we don’t know that user will enter a fix no. of values then
use SMA.
o In c programming, these variables are created by using some
functions and header files-
1. Malloc()
2. Calloc()
3. Realloc()
4. Free()
5. Stdlib.h
6. Malloc()
1. malloc():It means memory allocation.Return type of malloc is
void.Block created with the help of malloc() contain garbage value.

1. calloc():It means contiguous allocation.Blocks created by calloc()


function by default contain 0.
syntax
calloc(no. of block,size of each block);
Example
calloc(5,4);

Program
main()
{
int *p;
p=(int*)calloc(5,4);
}
 Access values-
*(P+0)=34
*(P+1)=55
2. realloc():It means reallocation.When we want to change the size
of a memory block which is created with the help of malloc() &
calloc() function,then we use reallock().
syntax
calloc(pointer returned by malloc()/calloc(),size of memory block);
Example
Void realloc(void *block,int size)
o In c++ programming, these variables are created by using some
keywords/operators
1. new
2. delete
1. new-It denotes a request for memory allocation on the free
storage.If sufficient memory is available,a new operator initializes
the memory and retuned the address of newly allocated &
initialized memory to the pointer variable.
Syntax
Pointer_variable=new data-type;
Example-
Float *p=new float;
Int *ptr=new int[5];
2. delete-It is an operator which is used to destroy array & non-
array(pointer) objects which are dynamically created by new
operator.
 delete can be used by either the delete operator or delete[]
operator.
 new operator is used for dynamic memory allocation which stores
variables on heap memory.It means delete operator deallocates
memory from the heap.
 The pointer to the object is not destroyed,the value or memory
block pointed by the pointer is destroyed.
 It has void return type which means it doesn’t return any value.
Syntax
delete pointer_name;
Or
delete[] array_name;

You might also like