0% found this document useful (0 votes)
2 views64 pages

Object Oriented Programming (OOP) (1)

The document provides an overview of Object Oriented Programming (OOP) concepts in C++, including classes, objects, access specifiers (public, private, protected), and inheritance. It explains the structure of classes, the significance of constructors and destructors, and various types of inheritance such as single, multilevel, and multiple inheritance. Additionally, it covers key OOP principles like encapsulation, polymorphism, and abstraction.

Uploaded by

hani.adeel77
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)
2 views64 pages

Object Oriented Programming (OOP) (1)

The document provides an overview of Object Oriented Programming (OOP) concepts in C++, including classes, objects, access specifiers (public, private, protected), and inheritance. It explains the structure of classes, the significance of constructors and destructors, and various types of inheritance such as single, multilevel, and multiple inheritance. Additionally, it covers key OOP principles like encapsulation, polymorphism, and abstraction.

Uploaded by

hani.adeel77
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/ 64

Object Oriented Programming (OOP)

By
Irfan Abdullah
CONTENTS
• Concept of Class and Object in OOP
• Private and Public access specifiers
• Concept of Encapsulation
• What are Constructor and Destructor?
• Types of Constructor
• Inheritance in Object Oriented Programming
• Inheritance Access Specifiers
• Types of Inheritance
• Polymorphism
• concept of Abstraction
• Overloading and Overriding in OOP
Classes in C++
• A class in C++ is the building block, that leads to Object-
Oriented programming. 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
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 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.
Classes in C++
• A Class is a user defined data-type which has data members and
member functions.
• Data members are the data variables and member functions are
the functions used to manipulate these variables and together
these data members and member functions defines the
properties and behavior 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 apply
brakes, increase speed etc.
Object in C++
• 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.
Defining Class and Declaring Objects
• 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.
• A class definition starts with the
keyword class followed by the
class name; and the class body,
enclosed by a pair of curly
braces. A class definition must
be followed either by a
semicolon or a list of
declarations.
Defining Class and Declaring Objects
• 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:
ClassName ObjectName;
• Following statements declare two objects of class Box.
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
• Both of the objects Box1 and Box2 will have their own copy of
data members.
Defining Class and Declaring Objects
// box 2 specification
#include <iostream>
Box2.height = 10.0;
using namespace std;
Box2.length = 12.0;
class Box {
Box2.breadth = 13.0;
public:
double length; // Length of a box
// volume of box 1
double breadth; // Breadth of a box
volume = Box1.height * Box1.length * Box1.breadth;
double height; // Height of a box
cout << "Volume of Box1 : " << volume <<endl;
};
int main() {
// volume of box 2
Box Box1; // Declare Box1 of type Box
volume = Box2.height * Box2.length * Box2.breadth;
Box Box2; // Declare Box2 of type Box
cout << "Volume of Box2 : " << volume <<endl;
double volume = 0.0; // Store the volume of a box here
return 0;
}
// box 1 specification
Box1.height = 5.0; • It produces the following result −
Box1.length = 6.0; Volume of Box1 : 210
Box1.breadth = 7.0; Volume of Box2 : 1560
Access Specifiers in C++
• In C++, there are three access specifiers:

• public - members are accessible from outside the class


• private - members cannot be accessed (or viewed) from outside the
class
• protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes.
Public Access Specifiers
• A public access specifier is accessible from int main() {
anywhere outside the class but within a // declare a class object
program. You can set and get the value of public Sample obj1;
variables without any member function. cout << "Enter your age: ";
• The public keyword is used to create public // store input in age of the obj1 object
members (data and functions). cin >> obj1.age;
#include <iostream> // call class function
using namespace std; obj1.displayAge();
// define a class return 0;
class Sample { }
// public elements
public:
• The output of the program is:
Enter your age: 20
int age;
Age = 20
void displayAge() {
cout << "Age = " << age << endl;
}
};
Private Access Specifiers
• A member variable or function define as private access specifier
cannot be accessed, or even viewed from outside the class. Only
the class and friend functions can access private members.
• The private keyword is used to create private members (data
and functions).
• By default, all the members of a class would be private, which
means until you label a member, it will be assumed a private
member
Private Access Specifiers
#include <iostream> int main() {
using namespace std; int ageInput;
// define a class // declare an object
class Sample { Sample obj1;
// private elements cout << "Enter your age: ";
private: cin >> ageInput;
int age; // call function and pass ageInput as argument
// public elements
public: obj1.displayAge(ageInput);
void displayAge(int a) { return 0;
age = a; }
cout << "Age = " << age << endl; • The out put of the program is
} Enter your age: 20
}; Age = 20
Protected Access Specifiers
• A protected member variable or function is very similar to a
private member, but it provided one additional benefit that they
can be accessed in child classes which are called derived classes.
• We will learn this is detail we discuss derived classes and
inheritance in next section. For now we can check following
example where we have derived one child class SmallBox from a
parent class Box.
Protected Access Specifiers
#include <iostream> void SmallBox::setSmallWidth( double wid ) {
using namespace std; width = wid;
class Box { }
protected:
double width; // Main function for the program
};
class SmallBox:Box { int main() {
// SmallBox is the derived class. SmallBox box;
public: // set box width using member function
void setSmallWidth( double wid ); box.setSmallWidth(5.0);
double getSmallWidth( void ); cout << "Width of box : "<< box.getSmallWidth()
}; << endl;
// Member functions of child class return 0;
double SmallBox::getSmallWidth(void) { }
return width ; • The outpu of the program is:
} Width of box : 5
Public and Private Access Specifiers
#include <iostream> int main()
using namespace std; {
class A A obj;
{ obj.getdata(4, 5);
private: obj.showdata();
int a, b; return (0);
public: }
void getdata(int x, int y) • The output of the program is
{ The sum of two private integer data members are = 9
a = x; The product of two private integer data members are =
b = y; 20
}
void showdata()
{
cout << "The sum of two private integer data
members are = " << a + b << endl;
cout << "The product of two private integer data
members are = " << a * b << endl;
}
};
Inheritance
• Inheritance is one of the key class Animal {
features of Object-oriented // eat() function
programming in C++. It allows // sleep() function
us to create a new class (derived };
class/sub class) from an existing
class (base class/ super class). class Dog : public Animal {
• The derived class inherits the // bark() function
features from the base class and };
can have additional features of
its own.
• To inherit from a class, use the :
symbol.
Why and when to use inheritance?
• Consider a group of vehicles. You • If we create a class Vehicle and write these
need to create classes for Bus, Car three functions in it and inherit the rest of
and Truck. The methods the classes from the vehicle class, then we
fuelAmount(), capacity(), can simply avoid the duplication of data
applyBrakes() will be same for all of and increase re-usability. Look at the
the three classes. If we create these below diagram in which the three classes
classes avoiding inheritance then we are inherited from vehicle class:
have to write all of these functions in
each of the three classes as shown in
below figure:

• Using inheritance, we have to write the


functions only one time instead of three
times as we have inherited rest of the
three classes from base class(Vehicle).
is-a relationship // Base class
class Vehicle {
public:
• Inheritance is an is-a relationship. We use string brand = "Ford";
inheritance only if an is-a relationship is present
between the two classes. void honk() {
• For example: cout << "Tuut, tuut! \n" ;
• A car is a vehicle. }
• Orange is a fruit. };
• A surgeon is a doctor. // Derived class
• A dog is an animal. class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Modes of Inheritance
• Public mode: If we derive a sub class 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 derived class.
• Protected mode: If we derive a sub class from a Protected
base class. Then both public member and protected members of
the base class will become protected in derived class.
• Private mode: If we derive a sub class from a Private base
class. Then both public member and protected members of the
base class will become Private in derived class.
Modes of Inheritance
class A class C : protected A
{ {
public: // x is protected
int x; // y is protected
protected: // z is not accessible from C
int y; };
private:
int z; class D : private A // 'private' is
}; default for classes
class B : public A {
{ // x is private
// x is public // y is private
// y is protected // z is not accessible from D
// z is not accessible from B };
};
Modes of Inheritance
• The below table summarizes the above three modes and shows
the access specifier of the members of base class in the sub class
when derived in public, protected and private modes:
Public Inheritance
#include <iostream> class PublicDerived : public Base {
using namespace std; public:
class Base { // function to access protected member from
private: Base
int pvt = 1; int getProt() {
protected: return prot;
int prot = 2; }
public: };
int pub = 3; int main() {
// function to access private member PublicDerived object1;
int getPVT() { cout << "Private = " << object1.getPVT() <<
endl;
return pvt;
cout << "Protected = " << object1.getProt()
} << endl;
}; cout << "Public = " << object1.pub << endl;
return 0;
}
Protected Inheritance
#include <iostream> class ProtectedDerived : protected Base {
using namespace std; public:
class Base { // function to access protected member from Base
private: int getProt() {
int pvt = 1; return prot;
protected: }
int prot = 2; // function to access public member from Base
public: int getPub() {
int pub = 3; return pub;
}
// function to access private member };
int getPVT() { int main() {
return pvt; ProtectedDerived object1;
} cout << "Private cannot be accessed." << endl;
}; cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Private Inheritance
#include <iostream> class PrivateDerived : private Base {
using namespace std; public:
class Base { // function to access protected member from Base
private: int getProt() {
int pvt = 1; return prot;
protected: }
int prot = 2; // function to access private member
public: int getPub() {
int pub = 3; return pub;
// function to access private member }
int getPVT() { };
return pvt; int main() {
} PrivateDerived object1;
}; cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Types of Inheritance in C++
• C++ supports six types of inheritance as follows:
• Single Inheritance
• Multilevel Inheritance
• Multiple Inheritance
• Heirarchical Inheritance
• Hybrid Inheritance
• Multipath Inheritance
Single Inheritance
• In single inheritance, a class • Syntax:
is allowed to inherit from only class subclass_name :
one class. i.e. one sub class is access_mode base_class
inherited by one base class {
only. //body of subclass
};
Single Inheritance
#include <iostream> int main()
using namespace std; {
// base class // creating object of sub class will
class Vehicle { // invoke the constructor of base classes
public: Car obj;
Vehicle() return 0;
{ }
cout << "This is a Vehicle" << endl; • The output of the program is
} This is a vehicle
};
// sub class derived from two base classes
class Car: public Vehicle{

};
Multilevel Inheritance
• In this type of inheritance, a
derived class is created from
another derived class.
Multilevel Inheritance
#include <iostream> class Car: public fourWheeler{
using namespace std; public:
// base class Car()
class Vehicle {
{ cout<<"Car has 4 Wheels"<<endl;
public: }
Vehicle() };
{ // main function
cout << "This is a Vehicle" << endl; int main()
} {
}; //creating object of sub class will
class fourWheeler: public Vehicle //invoke the constructor of base classes
{ public: Car obj;
fourWheeler() return 0;
{ }
cout<<"Objects with 4 wheels are • The output is
vehicles"<<endl;
} This is a Vehicle
}; Objects with 4 wheels are vehicles
Car has 4 Wheels
Multiple Inheritance
• Multiple Inheritance is a • Syntax:
feature of C++ where a class class subclass_name :
can inherit from more than access_mode base_class1,
one classes. i.e one sub class access_mode base_class2, ....
is inherited from more than {
one base classes. //body of subclass
};
Multiple Inheritance
#include <iostream> class Car: public Vehicle, public FourWheeler {
using namespace std;
// first base class };
class Vehicle {
public: // main function
Vehicle() int main()
{ {
cout << "This is a Vehicle" << endl; // creating object of sub class will
} // invoke the constructor of base classes
}; Car obj;
// second base class return 0;
class FourWheeler { }
public: • The output of the program is:
FourWheeler() This is a Vehicle
{ This is a 4 wheeler Vehicle
cout << "This is a 4 wheeler Vehicle" << endl;
}
};
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.
Hierarchical Inheritance
#include <iostream> class Bus: public Vehicle
using namespace std; {
// base class
class Vehicle };
{ // main function
public: int main()
Vehicle() {
{ // creating object of sub class will
cout << "This is a Vehicle" << endl; // invoke the constructor of base class
} Car obj1;
}; Bus obj2;
// first sub class return 0;
class Car: public Vehicle }
{ • The output of the program is
This is a Vehicle
}; This is a Vehicle
Hybrid (Virtual) Inheritance
• Hybrid Inheritance is
implemented by combining
more than one type of
inheritance. For example:
Combining Hierarchical
inheritance and Multiple
Inheritance.
Hybrid (Virtual) Inheritance
#include <iostream> // first sub class
using namespace std; class Car: public Vehicle
// base class {
class Vehicle
{ };
public: // second sub class
Vehicle() class Bus: public Vehicle, public Fare
{ {
cout << "This is a Vehicle" << endl;
} };
}; // main function
//base class int main()
class Fare {
{ // creating object of sub class will
public: // invoke the constructor of base class
Fare() Bus obj2;
{ return 0;
cout<<"Fare of Vehicle\n"; }
} • The output of the program is
}; This is a Vehicle
Fare of Vehicle
Multipath Inheritance
• A derived class with two base
classes and these two base
classes have one common
base class is called multipath
inheritance. An ambiguity can
arrise in this type of
inheritance.
Multipath Inheritance
int main()
#include<iostream> {
class ClassA ClassD obj;
{ //obj.a = 10; //Statement 1, Error
public: //obj.a = 100; //Statement 2, Error
int a; obj.ClassB::a = 10; //Statement 3
}; obj.ClassC::a = 100; //Statement 4
class ClassB : public ClassA obj.b = 20;
{ obj.c = 30;
public: obj.d = 40;
int b; cout<< "\n A from ClassB : "<< obj.ClassB::a;
}; cout<< "\n A from ClassC : "<< obj.ClassC::a;
class ClassC : public ClassA cout<< "\n B : "<< obj.b;
{ cout<< "\n C : "<< obj.c;
public: cout<< "\n D : "<< obj.d;
int c; return 0;
}; }
class ClassD : public ClassB, public ClassC
{ • The output of the program is
public: A from ClassB : 10
int d; A from ClassC : 100
}; B : 20
C : 30
D : 40
Encapsulation
• Encapsulation is an Object Oriented Programming concept that binds
together the data and functions that manipulate the data, and that keeps
both safe from outside interference and misuse. Data encapsulation led to
the important OOP concept of data hiding.

• Data encapsulation is a mechanism of bundling the data, and the functions


that use them and data abstraction is a mechanism of exposing only the
interfaces and hiding the implementation details from the user.

• C++ supports the properties of encapsulation and data hiding through the
creation of user-defined types, called classes. We already have studied that
a class can contain private, protected and public members. By default, all
items defined in a class are private.
Encapsulation
#include<iostream> int main()
using namespace std; {
class Encapsulation Encapsulation obj;
{
private: obj.set(5);
// data hidden from outside world
int x; cout<<obj.get();
return 0;
public: }
// function to set value of variable x • The output of the program is
void set(int a) 5
{
x =a; • In the above program the variable x is
} made private. This variable can be accessed
and manipulated only using the functions
// function to return value of variable x get() and set() which are present inside the
int get() class. Thus we can say that here, the
{ variable x and the functions get() and set()
return x; are binded together which is nothing but
} encapsulation.
};
Constructor
• A constructor is a member function of a class that has the same name
as the class name. It helps to initialize the object of a class. It can
either accept the arguments or not. It is used to allocate the memory
to an object of the class. It is called whenever an instance of the class
is created. It can be defined manually with arguments or without
arguments. There can be many constructors in class. It can be
overloaded but it can not be inherited or virtual. There is a concept of
copy constructor which is used to initialize a object from another
object.
• Syntax:
ClassName()
{
//Constructor's Body
}
Destructor
• Like constructor, deconstructor is also a member function of a class
that has the same name as the class name preceded by a tilde(~)
operator. It helps to deallocate the memory of an object. It is called
while object of the class is freed or deleted. In a class, there is always
a single destructor without any parameters so it can’t be oveloaded. It
is always called in the reverse order of the constructor. if a class is
inherited by another class and both the classes have a destructor then
the destructor of the child class is called first, followed by the
destructor of the parent or base class.
• Syntax:
~ClassName()
{
}
Implementation of Constructor and
Destructor
#include <iostream> int main()
using namespace std; {
class Z Z z1; // Constructor Called
{ int a = 1;
public: if(a==1)
// constructor {
Z() Z z2; // Constructor Called
{ } // Destructor Called for z2
cout<<"Constructor called"<<endl; return 0;
} } // Destructor called for z1
// destructor • The output of the program is
~Z() Constructor called
{ Constructor called
cout<<"Destructor called"<<endl; Destructor called
} Destructor called
};
Difference between Constructor and
Destructor
Constructor Destructor
• Constructor helps to initialize the object of a • Whereas destructor is used to destroy the
class. instances.
• It is declared as Classname( arguments if • Whereas it is declared as ~ ClassName( no
any ){Constructor’s Body }. arguments ){ };.
• Constructor can either accept an arguments or • While it can’t have any arguments.
not.
• It is called while object of the class is freed or
• A constructor is called when an instance or deleted.
object of a class is created.
• While it is used to deallocate the memory of an
• Constructor is used to allocate the memory to an object of a class.
instance or object.
• While it can’t be overloaded.
• Constructor can be overloaded.
• Here, it’s name is also same as the class name
• The constructor’s name is same as the class preceded by tiled (~) operator.
name.
• While in a class, there is always a single
• In a class, there can be multiple constructors. destructor.
• There is a concept of copy constructor which is • While here, there is no copy constructor
used to initialize a object from another object. concept.
Types of Constructors in C++
• Constructors are of three types:
• Default Constructor
• Parametrized Constructor
• Copy Constructor
Default Constructor
• Default constructor is the constructor class Cube
which doesn't take any argument. It {
has no parameter. public:
• Syntax: int side;
class_name(parameter1, parameter2, ...) Cube()
{ {
// constructor Definition side = 10;
} }
};
• In this case, as soon as the object is int main()
created the constructor is called which {
initializes its data members.
Cube c;
• If we have not defined a constructor in cout << c.side;
our class, then the C++ compiler will return 0;
automatically create a default }
constructor with an empty code and no
parameters. • The output is
10
Parameterized Constructor
• These are the constructors with parameter. Using this
constructor, you can provide different values to data members
of different objects, by passing the appropriate values as
argument.
• To create a parameterized constructor, simply add parameters
to it the way you would to any other function. When you define
the constructor’s body, use the parameters to initialize the
object.
• This is the preferred method to initialize member data.
Parameterized Constructor
#include <iostream> double calculateArea() {
using namespace std; return length * height;
}
// declare a class };
class Wall { int main() {
private: // create object and initialize data
double length; members
double height; Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
public: cout << "Area of Wall 1: " <<
wall1.calculateArea() << endl;
// create parameterized constructor
cout << "Area of Wall 2: " <<
Wall(double len, double hgt) { wall2.calculateArea() << endl;
// initialize private variables
length = len; return 0;
height = hgt; }
}
• The output of the program is
• Area of Wall 1: 90.3
• Area of Wall 2: 53.55
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);


Copy Constructor
#include <iostream>
using namespace std;
// declare a class int main() {
class Wall { // create an object of Wall class
private: Wall wall1(10.5, 8.6);
double length; // print area of wall1
double height; cout << "Area of Room 1: " << wall1.calculateArea() << endl;
public:
// parameterized constructor // copy contents of room1 to another object room2
Wall(double len, double hgt) { Wall wall2 = wall1;
// initialize private variables
length = len; // print area of wall2
height = hgt; cout << "Area of Room 2: " << wall2.calculateArea() << endl;
}
// copy constructor with a Wall object as parameter return 0;
Wall(Wall &obj) { }
// initialize private variables • The output of the program is
length = obj.length; Area of Room 1: 90.3
height = obj.height; Area of Room 2: 90.3
}
double calculateArea() {
return length * height;
}
};
Constructor Overloading
• Just like other member functions, constructors can also be
overloaded. Infact when you have both default and
parameterized constructors defined in your class you are having
Overloaded Constructors, one with no parameter and other with
parameter.

• You can have any number of Constructors in a class that differ


in parameter list.
Constructor Overloading
#include <iostream> int main()
using namespace std; {
class construct // Constructor Overloading
{ // with two different constructors
public: // of class name
float area; construct o;
// Constructor with no parameters construct o2( 10, 20);
construct()
{ o.disp();
area = 0; o2.disp();
} return 0;
// Constructor with two parameters }
construct(int a, int b) • The output of the program is
{ 0
area = a * b; 200
}
void disp()
{
cout<< area<< endl;
}
};
Polymorphism
• The term Polymorphism gets derived from the Greek word where
poly + morphos where poly means many and morphos means forms.
• In programming background, polymorphism can be broadly divided
into two parts. These are:
• Static Polymorphism
• Dynamic Polymorphism.
• Polymorphism is another concept of object-oriented programming
(OOPs). The attitude which lies beneath this concept is "single
interface having multiple implementations.“
• Example : a person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person posses different behavior in different
situations.
Polymorphism
• Polymorphism is mainly divided into two types:
• Compile time Polymorphism
• Runtime Polymorphism
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.
Compile Time Polymorphism:
// C++ program for function overloading // function with same name and 2 int parameters
#include <bits/stdc++.h> void func(int x, int y)
using namespace std; {
class Poly cout << "value of x and y is " << x << ", " << y << endl;
{ }
public: };
void func(int x) int main() {
{ Poly obj1;
cout << "value of x is " << x << endl; obj1.func(7);
} obj1.func(9.132);
obj1.func(85,64);
void func(double x) return 0;
{ }
cout << "value of x is " << x << endl; • The output of the program is
} • The value of x is 7
• The value of x is 9.132
• The value of x and y is 85, 64
Compile Time Polymorphism
• Operator 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.
Compile Time Polymorphism
// Operator Overloading void print()
#include<iostream> {
using namespace std; cout << real << " + i" << imag << endl;
class Complex { }
private: };
int real, imag; int main()
public: {
Complex(int r = 0, int i =0) Complex c1(10, 5), c2(2, 4);
{ Complex c3 = c1 + c2; // An example call to "operator+"
real = r; imag = i; c3.print();
} return 0 ;
// This is automatically called when '+' is used with }
// between two Complex objects • The output of the program is
Complex operator + (Complex const &obj) • 12 + i9
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
Runtime Polymorphism
• This type of polymorphism is achieved by Function Overriding.
• Function overriding: 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
#include <iostream> int main() {
using namespace std; //Parent class object
class A { A obj;
public: obj.disp();
void disp(){ //Child class object
cout<<"Super Class B obj2;
Function"<<endl; obj2.disp();
} return 0;
}; }
class B: public A{
public: • The output of the program is
void disp(){ • Super Class Function
cout<<"Sub Class Function"; • Sub Class Function
}
};
Abstraction
• Data abstraction is one of the most essential and important
feature 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.
Abstraction
Abstraction using Classes:
• We can implement Abstraction in C++ using classes. Class helps us to group data members
and member functions using available access specifiers. A Class can decide which data
member will be visible to outside world and which is not.
Abstraction in Header files:
• One more type of abstraction in C++ can be header files. For example, consider the pow()
method present in math.h header file. Whenever we need to calculate power of a number,
we simply call the function pow() present in the math.h header file and pass the numbers as
arguments without knowing the underlying algorithm according to which the function is
actually calculating power of numbers.
Abstraction using access specifiers:
• Access specifiers are the main pillar of implementing abstraction in C++. We can use access
specifiers to enforce restrictions on class members. For example:
• Members declared as public in a class, can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class. They are not
allowed to be accessed from any part of code outside the class.
Abstraction
#include <iostream> void display()
using namespace std; {
class implementAbstraction cout<<"a = " <<a << endl;
{ cout<<"b = " << b << endl;
private: }
int a, b; };
int main()
public: {
// method to set values of implementAbstraction obj;
// private members obj.set(10, 20);
void set(int x, int y) obj.display();
{ return 0;
a = x; }
b = y; • The output off the program is
} • a = 10
• b = 20
Advantages of Data Abstraction
• Helps the user to avoid writing the low level code
• Avoids code duplication and increases reusability.
• Can change internal implementation of class independently
without affecting the user.
• Helps to increase security of an application or program as only
important details are provided to the user.
Difference between Function Overloading
and Function Overriding
Function Overloading Function Overriding
• Function Overloading happens in the • Function Overriding is happens in the
same class when we declare same child class when child class overrides
functions with different arguments in parent class function.
the same class. • In function overriding the signature of
• In function overloading function both the functions (overriding function
signature should be different for all and overridden function) should be
the overloaded functions. same.
• Overloading happens at the compile • While overriding happens at run time
time thats why it is also known as which is why it is known as run time
compile time polymorphism. polymorphism.
• In function overloading we can have • In function overriding we can have
any number of overloaded functions. only one overriding function in the
child class.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy