0% found this document useful (0 votes)
2 views

unit3

The document outlines the course content for Object-Oriented Programming (OOP) in C++, covering key concepts such as classes, objects, constructors, destructors, inheritance, polymorphism, and function overloading. It explains the definitions and roles of classes and objects, the significance of constructors and destructors, and various types of inheritance. Additionally, it discusses the principles of polymorphism and provides examples of function and operator overloading.

Uploaded by

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

unit3

The document outlines the course content for Object-Oriented Programming (OOP) in C++, covering key concepts such as classes, objects, constructors, destructors, inheritance, polymorphism, and function overloading. It explains the definitions and roles of classes and objects, the significance of constructors and destructors, and various types of inheritance. Additionally, it discusses the principles of polymorphism and provides examples of function and operator overloading.

Uploaded by

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

UNIT-03

Course Content
• Object & Classes,
• Scope Resolution Operator,
• Constructors
• Destructors
• Friend Functions
• Inheritance,
• Polymorphism
• Overloading Functions & Operators
• Types of Inheritance
• Virtual functions.
• Introduction to Data Structures.
Prof. Mahima Jain
Asst. Professor
(CSE)
BASIC PRINCIPLES OF OOP

Prof. Mahima Jain


Asst. Professor
(CSE)
Class
• The building block of C++ that leads to Object Oriented
programming is a Class. It 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 class is like a blueprint for an object.

Prof. Mahima Jain


Asst. Professor
(CSE)
Defining Class

• A class is defined in C++ using keyword class followed by the


name of class. The body of class is defined inside the curly
brackets and terminated by a semicolon at the end.

Prof. Mahima Jain


Asst. Professor
(CSE)
contd..
• For Example: Consider the Class of Cars. There may be
many cars with different names and brand but all of them
will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range etc. So here,
Car is the class and wheels, speed limits, mileage are
their properties.
• In the above example of class Car,
the data member will be speed limit, mileage etc
member functions can be apply brakes, increase
speed etc.

Prof. Mahima Jain


Asst. Professor
(CSE)
Object

Object :
•An Object is an identifiable entity with some characteristics
and behaviour. An Object is an instance of a Class. When a
class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
•To use the data and access functions defined in the class,
you need to create objects.

Syntax : ClassName ObjectName;

Prof. Mahima Jain


Asst. Professor
(CSE)
contd...
• When a program is executed the objects interact by
sending messages to one another.
• Each object contains data and code to manipulate the
data.
• Objects can interact without having to know details of
each other’s data or code, it is sufficient to know the type
of message accepted and type of response returned by
the objects.

Prof. Mahima Jain


Asst. Professor
(CSE)
contd..

class person
{ char name[20];
int id;
public:
void getdetails(){}
};
int main()
{
person p1; // p1 is a object
}

Prof. Mahima Jain


Asst. Professor
(CSE)
Scope Resolution Operator
: : Scope resolution operator helps compiler to identify functions
of which class if two classes have the same name.

Prof. Mahima Jain


Asst. Professor
(CSE)
PROGRAM
{
cout << “Enter no”;
cin >> a >>b;
}
void add : : sum( )
{
c= a+b;
}
void add : : show( )
{
cout << “Numbers are = “<< a << “ “ << b;
cout << “sum =” <<c;
}
void main( )
{
add obj;
obj. get( );
obj.sum( );
obj. show( );
getch( );} Prof. Mahima Jain
Asst. Professor
(CSE)
Constructors
Constructor are special member function of a class with the
following properties
•They have the same name as that of the class
•They don’t have any return type not even void
•They are automatically called as soon as the object of
class is created i.e. their calling is implicit.
•They can’t be declared as static
•They can’t be declared as virtual

Prof. Mahima Jain


Asst. Professor
(CSE)
contd...
• Any class which does not contain any constructor then
compiler from itself supplier a constructor but it is hidden.
for programmer these constructors are default.
class fact
{

};
• Constructors are automatically called even when not
declared, at that time default constructors are called.
Default contractors are destroyed as soon as we declare
constructor.

Prof. Mahima Jain


Asst. Professor
(CSE)
Types of constructor

• Copy constructors
• Parameterized constructors
• Default Constructors

Prof. Mahima Jain


Asst. Professor
(CSE)
Default Constructor
Default constructor is the constructor which doesn’t take any
argument. It has no parameters.
#include <iostream>
class construct {
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20; }
}; Prof. Mahima Jain
Asst. Professor
(CSE)
Parameterized constructors
This is achieved by passing arguments to the constructor function
when the objects are created.
class Point {
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
Prof. Mahima Jain
Asst. Professor
(CSE)
COPY CONSTRUCTOR

• A copy constructor is a member function which initializes


an object using another object of the same class. A copy
constructor has the following general function prototype:

ClassName (const ClassName &old_obj);

Prof. Mahima Jain


Asst. Professor
(CSE)
Destructor
• Destructors are special member function of class which
have same name as that of the class but preceded with
the symbol of tilde (~). They are automatically called
whenever an object goes out of scope, that is ,it is about
to be destroyed

• When an object is created first function which is


automatically called is constructor & when object ends its
life the last function which is called is destructor which
can be used to deallocate the resource occupied by the
object.
Syntax: ~classname();
Prof. Mahima Jain
Asst. Professor
(CSE)
COMPARISION BETWEEN CONSTRUCTOR &
DESTRUCTOR
Constructor Destructor
It is special member function of a class it is special member fn of class having
having same name as that of the class. same name as that of the class but
preceded with the symbol of tilde

Constructors are automatically called as A destructor is also automatically called but


soon as object of class is created i.e. their whenever an object is about to be
calling is implicit destructor or goes out of scope thus these
calling is implicit.

Constructors can be parameterized. we can not pass parameters to a


destructor.
as Constructors accepts parameters they as they don’t accept parameters we can
can be overloaded & thus a class can have not overload then, thus a class can not
multiple constructors. have multiple destructor

Constructors are called in the orders in calling of destructor is always done in


which objects are created. reverse of the creation of objects.
constructors can not be declared as virtual. we can have virtual destructor in a class
Friend Functions

• A friend function can be given special


grant to access private and protected
members.

Prof. Mahima Jain


Asst. Professor
(CSE)
Syntax of friend function

class class_name
{

friend data_type function_name(argument/


s);

};
Program
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
Rectangle(int l, int w) {
length=l;
width=w;
} friend int calculateArea(Rectangle rect); // Friend function declaration
};
// Friend function definition
int calculateArea(Rectangle rect) {
return rect.length * rect.width;
}
int main() {
Rectangle rect(10, 5);
cout << "Area of the rectangle: " << calculateArea(rect) << endl;
return 0;
}
Inheritance

• The capability of a class to derive properties and


characteristics from another class is called Inheritance.
• To inherit means to acquire properties and features of an
existing entity into a newly created entity Like a child
acquires properties of his or her parents.
• The class which gets inherited is known as base class and
the class which inherits is known as derived class.
• by inheriting the members of base class it becomes
possible to access them through the objects of derive
class.
• The major advantage offered by principle of Inheritance is
“reusability and reliability” Prof. Mahima Jain
Asst. Professor (CSE)
Why and when to use inheritance?
• Consider a group of vehicles. You need to create classes
for Bus, Car and Truck. The methods fuelAmount(),
capacity(), applyBrakes() will be same for all of the three
classes. If we create these classes avoiding inheritance
then we have to write all of these functions in each of the
three classes as shown in below figure:

Prof. Mahima Jain


Asst. Professor
(CSE)
• You can clearly see that above process results in
duplication of same code 3 times. This increases the
chances of error and data redundancy. To avoid this type
of situation, inheritance is used.
• If we create a class Vehicle and write these three
functions in it and inherit the rest of the classes from the
vehicle class, then we can simply avoid the duplication of
data and increase re-usability.

Prof. Mahima Jain


Asst. Professor
(CSE)
#include <iostream> // Derived class for Bus
using namespace std; class Bus : public Vehicle {
// Base class for Vehicle
public:
class Vehicle {
void specificFunctionBus() {
public:
cout << "This is specific to the Bus." <<
void fuelAmount() {
endl;
cout << "Checking fuel amount..." <<
}
endl;
} };
void capacity() { // Derived class for Car
cout << "Checking passenger capacity..." class Car : public Vehicle {
<< endl; public:
} void specificFunctionCar() {
void applyBrakes() { cout << "This is specific to the Car." <<
cout << "Applying brakes..." << endl; endl;
} }
}; };
// Derived class for Truck
cout << "\nCar Actions:" << endl;
class Truck : public Vehicle {
car.fuelAmount();
public:
car.capacity();
void specificFunctionTruck() {
car.applyBrakes();
cout << "This is specific to the Truck."
car.specificFunctionCar();
<< endl;
}
cout << "\nTruck Actions:" << endl;
};
truck.fuelAmount();
int main() {
truck.capacity();
// Create objects for each derived class
truck.applyBrakes();
Bus bus;
truck.specificFunctionTruck();
Car car;
return 0;
Truck truck;
}
cout << "Bus Actions:" << endl;
bus.fuelAmount();
bus.capacity();
bus.applyBrakes();
bus.specificFunctionBus();
Types of Inheritance

• Single Inheritance: In single inheritance,


a class is allowed to inherit from only one
class. i.e. one sub class is inherited by one
base class only.

Prof. Mahima Jain


Asst. Professor
(CSE)
Types of Inheritance
• Multiple Inheritance: Multiple Inheritance is a feature of
C++ where a class can inherit from more than one
classes. i.e one sub class is inherited from more than
one base classes.
Types of Inheritance
• Multilevel Inheritance: In this type of inheritance, a
derived class is created from another derived class.
Types of Inheritance
• Hierarchical Inheritance: In this type of inheritance,
more than one sub class is inherited from a single base
class. i.e. more than one derived class is created from a
single base class.
Types of Inheritance
• Hybrid (Virtual) Inheritance: Hybrid Inheritance is
implemented by combining more than one type of
inheritance. For example: Combining Hierarchical
inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and
multiple inheritance:
Polymorphism
• The word polymorphism is derived from combination of t
wo words poly meaning multiple and morph means the
ability to have multiple forms.
• In other words if an entity can acquire multiple forms in
different situation we say that its behaviors is polymorphi
c.
• for eg in c++ it is possible for programmer to define oper
ator ‘+’ in such a way that it can be used to add two integ
ers as well as at the same time it can add two object or t
wo strings. we say that + behaves polymorphically .

Prof. Mahima Jain


Asst. Professor
(CSE)
Prof. Mahima Jain
Asst. Professor
(CSE)
• Compile time polymorphism: This type of
polymorphism is achieved by function overloading or
operator overloading.
• Function Overloading: When there are multiple
functions with same name but different parameters then
these functions are said to be overloaded. Functions
can be overloaded by change in number of
arguments or/and change in type of arguments.

Prof. Mahima Jain


Asst. Professor
(CSE)
function overloading Program
int main() {
#include <iostream> double radius, length, width, base, height;
using namespace std;

// Area of a circle
// Function to calculate the area of a circle
cout << "Enter the radius of the circle: ";
double area(double radius) {
return 3.14159 * radius * radius; cin >> radius;
} cout << "Area of the circle: " <<
area(radius) << endl;
// Function to calculate the area of a rectangle
double area(double length, double width) { // Area of a rectangle
return length * width; cout << "Enter the length and width of the
} rectangle: ";
cin >> length >> width;
cout << "Area of the rectangle: " <<
area(length, width) << endl;
return 0;
}
• Operating Overloading:C++ also provide option to
overload operators. For example, we can make the
operator (‘+’) for string class to concatenate two strings.
We know that this is the addition operator whose task is
to add two operands. So a single operator ‘+’ when
placed between integer operands , adds them and when
placed between string operands, concatenates them.

Prof. Mahima Jain


Asst. Professor
(CSE)
Program 2
#include <iostream> // Display method
using namespace std;
void display() {
// Complex number class
cout << real << " + " << imag << "i"
class Complex {
<< endl;
private: }
double real, imag; };
public:
// Constructor
int main() {
Complex(double r = 0, double i = 0) : real(r),
imag(i) {} Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2; // Using
// Overloading + operator overloaded + operator
Complex operator+(const Complex &c) {
c3.display(); // Output: 4 + 6i
return Complex(real + c.real, imag +
c.imag); return 0;
} }
• Runtime Polymorphism:This type of polymorphism is
achieved by Function Overriding. Function
overriding on the other hand 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.

Prof. Mahima Jain


Asst. Professor
(CSE)
Overloading Of Unary Operator As
(Pre Increment)
void operator ++( );
class counter void show( )
{ {
int count; cout << count <<end1;}
public: };
counter( ) void counter : : operator ++ ( )
{ {++ count;
count =0; }
} void main( )
counter (int c) {
{ counter a = 10;
a.show( );
count = c
++ a; // a. operator + +
}
( );
a. show( );
}
#include <iostream>
using namespace std;
int main() {
class Animal { Animal* animal;
public: Dog dog;
virtual void sound() { // Virtual function for
overriding
cout << "Animal makes a sound" << endl; animal = &dog; // Polymorphism: Base
}
class pointer to derived class object
}; animal->sound(); // Calls the
overridden method in the derived
class Dog : public Animal {
class (Dog barks)
public:
void sound() { // Overriding the base class return 0;
method }
cout << "Dog barks" << endl;
}};
Introduction to Data Structure
• A data structure is a systematic way of organizing, managing,
and storing data in a computer so that it can be accessed and
modified efficiently.
• Data structures play a fundamental role in computer science
and programming, as they provide the means to handle large
amounts of data effectively for a variety of operations, such
as searching, sorting, and data manipulation.

• Program = Algorithm + Data Structure


Classification of Data Structure
• Linear Data Structure:

– Elements are arranged in one dimension ,also


known as linear dimension.
– Example: lists, stack, queue, etc.
• Non-Linear Data Structure
– Elements are arranged in one-many, many-one
and many-many dimensions.
– Example: tree, graph, table, etc.
Array:

• An array is a collection of data items stored at contiguous


memory locations. The idea is to store multiple items of the
same type together. This makes it easier to calculate the
position of each element by simply adding an offset to a base
value, i.e., the memory location of the first element of the
array (generally denoted by the name of the array).

Linked list
• Like arrays, Linked List is a linear data structure. Unlike arrays,
linked list elements are not stored at a contiguous location;
the elements are linked using pointers.
STACK
• Stack is a linear data structure which follows a particular
order in which the operations are performed. The order may
be LIFO(Last In First Out) or FILO(First In Last Out). In stack, all
insertion and deletion are permitted at only one end of the
list.

Stack Operations:
• push(): When this operation is performed, an element is
inserted into the stack.
• pop(): When this operation is performed, an element is
removed from the top of the stack and is returned.
• top(): This operation will return the last inserted element that
is at the top without removing it.
• size(): This operation will return the size of the stack i.e. the
total number of elements present in the stack.
• isEmpty(): This operation indicates whether the stack is
empty or not.
QUEUE
• Like Stack, Queue is a linear structure which follows a
particular order in which the operations are performed. The
order is First In First Out (FIFO). In the queue, items are
inserted at one end and deleted from the other end.
• A good example of the queue is any queue of consumers for a
resource where the consumer that came first is served first.
• The difference between stacks and queues is in removing. In a
stack we remove the item the most recently added; in a
queue, we remove the item the least recently added.
Queue Operations

• Enqueue(): Adds (or stores) an element to the end of the


queue..
• Dequeue(): Removal of elements from the queue.
• Peek() or front(): Acquires the data element available at the
front node of the queue without deleting it.
• rear(): This operation returns the element at the rear end
without removing it.
• isFull(): Validates if the queue is full.
• isNull(): Checks if the queue is empty.
GRAPH
• Graph is a data structure that consists of a collection of nodes
(vertices) connected by edges. Graphs are used to represent
relationships between objects and are widely used in
computer science, mathematics, and other fields.
• Graphs can be used to model a wide variety of real-world
systems, such as social networks, transportation networks,
and computer networks.

TREE
• Tree Data Structure is a non-linear data structure in which a collection
of elements known as nodes are connected to each other via edges
such that there exists exactly one path between any two nodes.

You might also like