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

Unit Iv CPP

Operator overloading and inheritance are discussed. Operator overloading involves defining operators like + and - for user-defined types. It can be done using member functions or non-member friend functions. Inheritance allows a derived class to inherit attributes and behaviors from a base class. Single inheritance where a derived class inherits from only one base class is described. Public inheritance results in public members of the base class becoming public in the derived class, while private inheritance makes them private.

Uploaded by

230603.it
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit Iv CPP

Operator overloading and inheritance are discussed. Operator overloading involves defining operators like + and - for user-defined types. It can be done using member functions or non-member friend functions. Inheritance allows a derived class to inherit attributes and behaviors from a base class. Single inheritance where a derived class inherits from only one base class is described. Public inheritance results in public members of the base class becoming public in the derived class, while private inheritance makes them private.

Uploaded by

230603.it
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 127

UNIT IV

Operator Overloading - Overloading Using Friend


functions – Inheritance – Types of inheritance – Virtual
Base Class - Abstract Class – Constructors in Derived
Classes - member class: nesting of classes. Pointer to
objects – this pointer- Pointer to derived Class - Virtual
functions – Pure Virtual Functions – Polymorphism
Over Loading

Creating two or more members having the same name but different in
number or type of parameter/arguments is known as overloading.

Types of overloading

❖ Function Over Loading


❖ Operator Over Loading

Function Overloading

Function Overloading is defined as the process of having two or more


function with the same name. In function overloading, the function is
redefined by using either different types of arguments or a different
number of arguments. It is only through these differences compiler can
differentiate between the functions.
Example Program

#include<iostream>
using namespace std;
class Calculate
{
public:
int add(int a,int b)
{
return a + b;
}

int add(int a, int b, int c)


{
return a + b + c;
}
};
int main(void)
{
Calculate C;
cout << "Sum of Two Numbers is : " << C.add(10,20) << endl;
cout << "Sum of Three Numbers is : " << C.add(12,20,23);
return 0;
}

Output

Sum of Two Numbers is : 30


Sum of Three Numbers is : 55
Syntax for C++ Operator Overloading

To overload an operator, we use a special operator function. We define


the function inside the class or structure whose objects/variables we
want the overloaded operator to work with.

class className
{ ... .. ...
public returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};

Here, returnType is the return type of the function.


operator is a keyword.
symbol is the operator we want to overload. Like: +, <, -, ++, etc.
arguments is the arguments passed to the function.
Program Example

#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex()
{
real =0;
imag = 0;
}
void input() {
cout << "Enter Real part : ";
cin >> real;
cout << "\nEnter Imaginary part : ";
cin >> imag; }
Complex operator + (Complex c2) // Operator overloading
{
Complex temp;
temp.real = real + c2.real;
temp.imag = imag + c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number : "<< real << imag << "i";
else
cout << "Output Complex number : " << real << " + " << imag <<"i";
}
};
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number : \n";
c1.input();
cout << endl;
cout<<"Enter second complex number : \n";
c2.input();
/* In case of operator overloading of binary
operators in C++ programming, the object on right hand
side of operator is always assumed as argument by
compiler.*/
result = c1 + c2;
result.output();
return 0;
}
Output

Enter first complex number :


Enter Real part : 5
Enter Imaginary part : 5
Enter second complex number :
Enter Real part : 5
Enter Imaginary part : 5
Output Complex number : 10 + 10i
Introduction

Data hiding is a fundamental concept of object-oriented programming. It


restricts the access of private members from outside of the class.
Similarly, protected members can only be accessed by derived classes and
are inaccessible from outside.
For example,
class MyClass
{
private:
int member1;
};
int main()
{
MyClass obj; // Error! Cannot access private members from here.
obj.member1 = 5;
}
However, there is a feature in C++ called friend functions that break this
rule and allow us to access member functions from outside the class.
friend Function

A friend function can access the private and protected data of a class. We
declare a friend function using the friend keyword inside the body of the
class.

Syntax

class className
{
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Characteristics of a Friend function:

1. The function is not in the scope of the class to which it has been
declared as a friend.
Characteristics of a Friend function: contd…
2. It cannot be called using the object as it is not in the scope of that
class.
3. It can be invoked like a normal function without using the object.
4. It cannot access the member names directly and has to use an object
name and dot membership operator with the member name.
5. It can be declared either in the private or the public part.
Program Example

#include<iostream>
using namespace std;
class integer
{
int num1, num2;
public:
void setValue()
{
num1 = 50;
num2 = 30;
}
friend int mean(integer s); //Declaration of friend Function
};
int mean(integer s) //friend function definition
{
return int(s.num1+s.num2) / 2.0;
}
int main()
{
integer c;
c.setValue();
cout<< "Mean value:" <<mean(c);
return 0;
}

Output
Mean value:40
Important points about operator overloading using friend function

1. An overloaded operator friend could be declared in either private or


public section of a class.

2. When an operator overloaded function is a friend function, it takes two


operands of user-defined data type.

3. When redefining the meaning of an operator by operator overloading


friend function, we cannot change its basic meaning. For example, we
cannot redefine minus operator to divide two operands of user-defined
data-type.
Program Example
#include <iostream>
using namespace std;
class Complex
{
private:
float real;
float imag;
public:
Complex()
{
real =0;
imag = 0;
}
void input()
{
cout << "Enter Real part : ";
cin >> real;
cout << "\nEnter Imaginary part : ";
cin >> imag;
}
// Operator overloading using Friend function
friend Complex operator + (Complex c1, Complex c2);
void output()
{
if(imag < 0)
cout << "Output Complex number : "<< real << imag << "i";
else
cout << "Output Complex number : " << real << " + " << imag << "i";
}
};

Complex operator+(Complex c1, Complex c2)


{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return(temp);
}
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number : \n";
c1.input();
cout << endl;
cout<<"Enter second complex number : \n";
c2.input();
result = c1 + c2;
result.output();
return 0;
}
Output

Enter first complex number :


Enter Real part : 9
Enter Imaginary part : 9
Enter second complex number :
Enter Real part : 10
Enter Imaginary part : 10
Output Complex number : 19 + 19i
When we overload a unary operator, we need to pass one argument.

❖ When we overload a binary operator, we need to pass two arguments.


❖ The friend function in C++ can access the private data members of a
class directly.
❖ An overloaded operator friend could be declared in either the private or
public section of a class.
❖ When redefining the meaning of an operator by operator overloading
the friend function, we cannot change its basic meaning.
For example, we cannot redefine plus operator + to multiply two operands
of a user-defined data type
Inheritance:

The mechanism of deriving a new class from an old one is called


inheritance. The old class is referred to as the base class and the new one is
called the derived class or subclass.

Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Single Inheritance is defined as the inheritance in which a derived class
is inherited from the only one base class.

In the diagram under Single inheritance box labelled “Base Class” is the
base class or Parent Class, and box labelled “Derived Class” is the Child
Class derived class.

The child class can inherit all the members of the base class according to
the visibility mode (i.e., private, protected, and public) that is specified
during the inheritance.
Syntax

class BaseClass
{
----
---- // code of class BaseClass
}

class DerivedClass : AccessModifier BaseClass


{
----
---- // code of class DerivedClass
}
Defining derived classes

class derived-class-name : visibility-mode base-class -name


{
….//
….// members of derived class
…//
};

The colon indicates that the derived-class-name is derived from the base-
class name.
The Visibility mode is optional and, if present, may be either private or
public.
The default Visibility-mode is private. Visibility mode specifies whether the
features of the base class Are- privately derived or publicly derived.
Examples:

class ABC: private XYZ // private derivation


{
members of ABC
};

class ABC: public XYZ // public derivation


{
members of ABC
};

class ABC: XYZ // private derivation by default


{
members of ABC
};
When a base class is privately inherited by a derived class, "public
members' of the base class become "private members” of the derived class
and therefore the public members of the base class can, only be accessed
by the member functions of the derived class, They are inaccessible to the
objects of the derived class.

Remember, a public member of a class can be accessed by its own objects


using the dot operator. The result is that no member of the base class is
accessible to the objects of the derived class .
On the other hand, when the base class is publicly inherited, 'public
members" of the base class become 'public members” of the derived
class and therefore they are accessible to the objects of the derived class.

In both the cases, the private members are not inherited and therefore ,
the private members of a base class will never become the members of
its derived class.

A base class B and a derived class D. The class B contains one private
data member, one public data member, and three public member
functions. The class D contains one private data member and two public
member functions.
SINGLE INHERITANCE : PUBLIC
#include <iostream.h>
using namespace std;
class B
{
int a; // private; not inheritable
public:
int b; // public; ready for inheritance
void get_ab();
int get_a(void);
void show_a(voi d)
};
class D : public B // public derivation
{
int c;
public:
void mul (void);
void display (void);
};
Void B :: get_ab (void);
{ a=5;b=10;}
int B:: get_a()
{
return a;
}
void B show_a{)
{
cout « a ;
}
void D :: mul()
{
c=b*get_a();
}
void D :: display()
{
cout « “a = " <<qet_a();
cout « 'b = " <<b;
cout «”c = " <<c;
}
Int main()
{
D d;
d.get_ab();
d.mul ();
d.show_a();
d.display();
}

Output
a=5
a =5
b =10
c = 50
a=5
b= 20
c = 100
SINGLE INHERITANCE : PRIVATE

#include <iostream.h>
using namespace std;
class B
{
Int a; // private; not inheritable
public:
int b; // public; ready for inheritance
void get_ab();
int get_a(void);
void show_a(voi d)
};
class D : private B //private derivation
{
int c;
public:
void mul (void);
void display (void);
};
void B :: get_ab(void);
{
Cout<<”enter a and b”;
Cin>>a>>b
}
int B:: get_a()
{ return a; }
void B :: show_a{)
{
cout « a ;
}
void D :: mul()
{
get_ab();
c=b*get_a();// a can’t be used directly
}
void D :: display()
{
Show_a()
cout « 'b = " <<b;
cout «”c = " <<c;
}
int main()
{
D d;
d.mul (); //d.get_ab(); won’t work Result
OUTPUT
d.display(); //d.show_a();won’t work A=5
//d.b=20; b has the private data. won’t work B=10
d.mul (); C=50
d.display();
}
Making a Private Member Inheritable

C++ provides a third visibility modifier, protected, which serve a limited


purpose in inheritance.
A member declared as protected is accessible by the member functions
within its class and any class immediately derived from it.
It cannot be accessed by the functions outside these two classes. A class
can now use all the three visibility modes as illustrated below:
class alpha
{
private:
…... // optional
……// visible to member functions
……// within its class
Protected:
…// visible to member functions
…// of its own and derived class
Public:
….// visible to all functions in the program
};
When a protected member is inherited in public mode, it becomes
protected in the derived class too and therefore is accessible by the
members functions of the derived class.

It is also ready for further inheritance, A protected member,


inherited in the private mode derivation, becomes private in the
derived class. Although it is available to the member functions of
the derived class, it is not available for further inheritance (since
private members cannot be inherited).
MULTILEVEL INHERITANCE

The class A serves as a base class for the derived class B„ which in turn
serves as a base class for the derived class C. The class B is known as
intermediate base class since it provides a link for the inheritance
between A and C. The chain ABC is known as inheritance path.
Example

Assume that the test results of a batch of students are stored in three
different classes . Class student stores the roll-number, class test store the
marks obtained in two subjects and class result contains the total marks,
obtained in the test. The class result can inherit the details of the marks
obtained in the test and the roll-number of students through multilevel
inheritance
class student
{
Protected:
int roll_number;
public:
void get_number(int );
void put_number (void) ;
};

void student ::get_number(int a)


{
Roll_ number=a;
}
void student:: put_number()
{
cout « "Roll Number: “ « roll_number « "\n";
}
class test : public student // First level derivation
{
protected:
float subl;
float sub2;
public:
void get_marks (float , float);
void put_mark(void);
}
void test ::get_marks(float x, float y)
{
Sub1 = x;
Sub2 = y;
}
void test:: put _marks()
{
cout « "marks in SUB1 =" subl « "\n";
cout « "marks fn SUB2= " « sub2 « "\n";
}
class result : public test // Second level derivation
{
float total; // private by default
public:
void display(void);
};
Program

Include <iostream.h>
class student
{
Protected:
int roll_number;
public:
void get_number(int );
void put_number (void) ;
};
void student ::get_number(int a)
{
Roll_ number=a;
}
void student:: put_number()
{
cout « "Roll Number: “ « roll_number « "\n";
}
class test : public student // First level derivation
{
protected:
float subl;
float sub2;
public:
void get_marks (float , float);
void put_mark(void);
}
void test ::get_marks(float x, float y)
{ Sub1 = x; Sub2 = y; }
void test:: put _marks()
{
cout « "marks in SUB1 =" subl « "\n";
cout « "marks fn SUB2= " « sub2 « "\n";
}
class result : public test // Second level derivation
{
float total; // private by default
public:
void display(void);
};
void result :: display(void)
{
Total= sub1+sub2;
Put_number();
Put_mark();
Cout<<”total=”<<total;
}
main() {
Result student1
Student1.get_number(1000);
Student1.get_markr(85,95);
Student1.display();
}
Multiple inheritance

A class can inherit the attributes of two or more classes , This is


known As multiple inheritance. Multiple inheritance allows us to
combine the features of several existing classes as a starting point for
defining new classes. A derived class derived from two or more base
classes. It is like a child inheriting the physical features of one parent
and the intelligence of another
The syntax of a derived class with multiple base class as follows:
class D: visibility B-1 , visibility B-2 ...
{
……
…….
……( Body of D )
}

Where visibility may be either public or private. The base class are
separated by commas.

Example;
class P : public M , public N
{
public:
void display(void);
}
Program

class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;;
public:
void get_n(int);
};
Class p : public M , Public N
{
Public :
Void display(void);
};
void M : : get_m(int x)
{
m=x;
}
void N :: get_n(int y)
{
n= y:
}
void P :: display(void)
{
cout « “m=”<<m;
cout<< "n =”« n ;
cout<<”m*n=” <<m*n;
}
main()
{
P p;
p.get_m(10);
p.get_n(20);
p.display();
}
Output
m=10
n=20
m*n=200
Hybrid Inheritance

Hybrid Inheritance: - This is a Mixture of two or More Inheritance and


in this Inheritance a Code May Contains two or Three types of
inheritance in Single Code. It consist of multilevel and multiple
inheritance .

Student

Sports
Test

Result
include <iostream.h>
class student
{
protected:
int roll_number;
public:
void get_number (int a)
{
Roll_ number= a;
}
void put_number (void)
{
cout "Roll No=”" « roll_number;
}
};
class test : public student
{
protected:
float part1, part2;
public:
void get_ marks(float x, float y)
{ Part1=x; part2 = y; }
yoid put_Marks(void)
{
cout « marks obtained: " « "\n"
cout<<"Part1 =" « part1;
cout« "Part2= " « part2 "\n”;
} };
class sports
{
protected:
float score;
public:;
void get_ score(float s)
{
Score=s;
}
void put_score(void)
{
cout « 'Sports wt:= " « score ;
} };
class result :: public test, public sports
{
float total ;
public;
void display (void)
};
void result :: display(void)
{
total = part1+ part2 + score;
put_number();
put_marks();
put_score();
cout « "Total Score: " « total;
}
main()
{
result student1;
student_1.get_number(1234);
student_1.get_marks(78,88);
student_1.get_score(6);
student_1.display();
}
Hierarchical Inheritance

Hierarchical Inheritance: Inheriting is a method of inheritance


where one or more derived classes is derived from common
base class.
#include<iostream.h>
class A //Base Class
{
public:
int a,b;
void getnumber()
{
cout<<"\n\nEnter Number :\t";
cin>>a;
}
};
class B : public A //Derived Class 1
{
public:
void square()
{
getnumber(); //Call Base class property
cout<<"\n\n\tSquare of the number :\t"<<(a*a);
}
};
class C :public A //Derived Class 2
{
public:
void cube()
{
getnumber(); //Call Base class property
cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
}
};

int main()
{
B b1; //b1 is object of Derived class 1
b1.square(); //call member function of class B
C c1; //c1 is object of Derived class 2
c1.cube(); //call member function of class C
}
Enter Number : 2
Square of the number : 4
Enter Number : 3
Cube of the number :: 27
Virtual Base Classes

Virtual Base Classes require the use of both the multiple and multilevel
inheritance. Consider a situation where all the three kinds of inheritance,
namely, multilevel, multiple and hierarchical inheritance, are involved, The
'child' has. two direct base classes 'parent1' and 'parents2’ which
themselves have a common base class 'grandparent'. The 'child' inherits the
traits of 'grandparent' via two separate paths. It can also inherit directly as
shown by the broken line. The 'grandparent‘ is sometimes referred to as
indirect have class.
All the public and protected members of grandparent are inherited into
'child' twice, first via parentl1 and again via 'parent2', This means, 'child'
would have duplicate sets of the members inherited from 'grandparent'.
The duplication of inherited members due to these multiple paths can be
avoided by using the common base class (ancestor class) as virtual base
class.
class A
{
….
….
}
Class Bl : virtual public A // parent1
{
….
….
}
class B2 : public virtual A // parent2
{
….
….
};
class C : public B1, public B2 // child
{
….
…. // only one copy of A will be inherited
}
Students contains roll number. This roll number will be inherited test class.
So test class contains roll number. Students contains roll number. this roll
number will be inherited sports class. So sports class contains roll number.
Now test class and sports class will be inherited the result class . so the
result class contains roll number twice.
PROGRAM -VIRTUAL BASE CLASS

include <1ostream.h>
Class student
{
Protected:
Int roll_number;
Public:
void get_number(int a)
{
Roll_ number = a;
}
void put_number (void)
{
Cout<< "roll No=”,<< roll_number « '\n";
};
class test : virtual public student
{
protected:
float partl, part2;
public:
void get_marks( float x, float y)
{
part1= x ;
part2= y;
}
void put_marks(void)
{
cout « "Marks obtained=”;
cout<<part1;
cout<<part2;
}
class sports : public virtual student
{
protected;
float score;
public:
void get_ score(float s)
{
score =s;
}
void put_score(void)
{
cout "Sports wt=”<< score;
};
class result : public test, public sports
{
Float total;
public:
void display (void);
}
void result :: display(void)
{
total = part1+ part2 + score;
put_number ( );
Put_marks();
put_score();
cout<<” Total Score: "<< total;
}

main()
{
result student_l;
stuctent_l .get_number(678) -„
student_1.get_marks(50.9,67.8);
student_l . get_score(7.0);
student_l.display();
return 0;
}
An abstract class is a class that is designed to be specifically used as a
base class. An abstract class contains at least one pure virtual function.

We declare a pure virtual function by using a pure specifier (= 0) in the


declaration of a virtual member function in the class declaration. In other
words, a function that has no definition. These classes cannot be
instantiated.
The classes inheriting the abstract class must provide a definition for the
pure virtual function; otherwise, the subclass would become an abstract
class itself.

C++ Pure Virtual Functions


Pure virtual Functions are virtual functions with no definition. They start
with virtual keyword and ends with = 0. Here is the syntax for a pure
virtual function,

virtual void functionname() = 0;


Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's
just the way we define pure virtual functions.

Pure virtual functions are used

❖ if a function doesn't have any use in the base class


❖ but the function must be implemented by all its derived classes

Example
Suppose, we have derived Triangle, Square and Circle classes from the
Shape class, and we want to calculate the area of all these shapes. In this
case, we can create a pure virtual function named calculateArea() in the
Shape. Since it's a pure virtual function, all derived classes Triangle, Square
and Circle must include the calculateArea() function with implementation.
A pure virtual function doesn't have the function body and it must end with
= 0.
For example

class Shape
{
public:

virtual void calculateArea() = 0; // creating a pure virtual function


};
Example Program Abstract Class

#include <iostream>
using namespace std;
class Shape // Abstract class
{
protected:
float dimension;
public:
void getDimension()
{
cin >> dimension;
}
virtual float calculateArea() = 0; // pure virtual Function
};
class Square : public Shape // Derived class
{
public:
float calculateArea()
{
return dimension * dimension;
}
};

class Circle : public Shape // Derived class


{
public:
float calculateArea()
{
return 3.14 * dimension * dimension;
}
};
int main()
{
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
Output

Enter the length of the square: 10


Area of square: 100

Enter radius of the circle: 30


Area of circle: 2826
Characteristics of Abstract Class

1. A class is abstract if it has at least one pure virtual function.


2. Abstract Classes cannot be instantiated, i.e. We cannot create an object of
an abstract class. But pointers and references of Abstract Class types can be
created.
3. Classes that inherit the Abstract Class must implement all pure virtual
functions. If they do not, those classes will also be treated as abstract
classes.
4. If we do not override the pure virtual function in derived class, then
derived class also becomes abstract class.
5. An abstract class can have constructors.
6. An abstract class in C++ can also be defined using struct keyword
Constructors

Constructor in C++ is a special method that is invoked automatically at


the time of object creation. It is used to initialize the data members of
new objects.
The constructor in C++ has the same name as the class. Constructor is
invoked at the time of object creation. It constructs the values i.e.
provides data for the object at the time of object creation. There fore it is
known as constructors. Constructor does not have a return value, hence
they do not have a return type.

Derived Class

A derived class is a class created or derived from another existing class.


The existing class from which the derived class is created through the
process of inheritance is known as a base class.
Derived classes are used for augmenting the functionality of base class by
adding or modifying the properties and methods to suit the requirements
of the specialization necessary for derived class.
Constructors in Derived Classes
1. Whenever object of a class is created, the default constructor of that
class is invoked automatically to initialize the members of the class.
2. If a class is inherited from another class and an object of the derived
class is created , it is clear that the default constructor of the derived
class will be invoked but before that, the default constructor of all of
the base classes will be invoked
3. That is the order of invocation is that the base class’s default
constructor will be invoked first and then the derived class’s default
constructor will be invoked.
Example Program :

#include <iostream>
using namespace std;
class Parent // Base Class
{
public:
Parent() // Base Class Constructor
{
cout << "Inside Base Class" << endl;
}
};
class Child : public Parent // Child Class
{
public:
Child() // Clild Class Constructor
{
cout << "Inside Child Class" << endl;
}
};

int main() // main() function


{
Child object; // Creating object of Child Class
return 0;
}

Output:
Inside Base Class
Inside Child Class
Member Class Class
A class in C++ is a user-defined type or data structure declared with
keyword class that has data and functions (also called member
variables and member functions) as its members whose access is
governed by the three access specifiers private, protected or public.
By default access to members of a C++ class is private Nested ClassA
declaration of a class may appear within another class. Such
declaration declares a nested class.
Explanation

1. A nested class is a class which is declared in another enclosing class. A


nested class is a member and as such has the same access rights as any
other member.
2. Member functions of a nested class follow regular access rules and
have no special access privileges to members of their enclosing
classes. Member functions of the enclosing class have no special
access to members of a nested class.
3. The scope of a nested class is valid only within the scope of the
enclosing class. This increases the use of encapsulation and creates
more readable and maintainable code
Syntax:

class EnclosingClass
{
class NestedClass
{
---
---
};

};
Pointer to Objects

A pointer is a variable that stores the memory address of another


variable (or object) as its value. A pointer aims to point to a data type which
may be int, character, double, etc.
Pointers to objects aim to make a pointer that can access the object,
not the variables. Pointer to object in C++ refers to accessing an object.
There are two approaches by which you can access an object. One is directly
and the other is by using a pointer to an object in c++.
A pointer to an object in C++ is used to store the address of an object.
For creating a pointer to an object in C++, we use the following syntax
Classname * pointertoobject;
For storing the address of an object into a pointer in c++, we use the
following syntax
Pointertoobject = &objectname;
After storing the address in the pointer to the object, the member
function can be called using the pointer to the object with the help of an
arrow operator [ ->].
Pointer to Objects Program 1
#include <iostream>
using namespace std;
class MyClass
{
int num;
public:
void setNumber(int value)
{
num = value;
}
void showNumber();
};

void MyClass::showNumber()
{
cout << "The Number is "<<num << "\n";
}
int main()
{
MyClass object, *p; // an object is declared and a pointer to it
object.setNumber(100); // object is accessed directly
object.showNumber();
p = &object; // the address of the object is assigned to p
p->showNumber(); // object is accessed using the pointer
return 0;
}

Output
The Number is 100
The Number is 100
Pointer to Objects Program 2

#include<iostream>
using namespace std;
class Complex
{
int real, imaginary;
public:
void put_Data()
{
cout << "The real part is “ << real << endl;
cout << "The imaginary part is “ << imaginary << endl;
}
void set_Data(int x, int y)
{
real = x;
imaginary = y;
}
};
int main()
{
Complex *ptr = new Complex;
ptr->set_Data(1, 54);
ptr->put_Data();
Complex *ptr1 = new Complex[4]; // Array of Objects
ptr1->set_Data(1, 4);
ptr1->put_Data();
return 0;
}

Output
The real part is 1
The imaginary part is 54
The real part is 1
The imaginary part is 4
this Pointer

• Every object in C++ has access to its own address through an


important pointer called this pointer. The this pointer is an implicit
parameter to all member functions. Therefore, inside a member
function, this may be used to refer to the invoking object.
• this pointer in C++ stores the address of the class instance, which is
called from the member function that enables functions to access the

correct object data members.


• Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
• The this pointer is a pointer accessible only within the non-static
member functions of a class, struct, or union type. It points to the
object for which the member function is called. Static member
functions don't have a this pointer.
Syntax this

this->member_identifier (data member)

There can be 3 main usage of this keyword in C++.

❖ It can be used to pass current object as a parameter to another method.


❖ It can be used to refer current class instance variable.
❖ It can be used to declare indexers.
this Pointer Program
#include<iostream>
using namespace std;
class Employee
{
public:
int id;
string name;
float salary;
Employee(int id,string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Employee e1 = Employee(101,"Sonoo",890000);
Employee e2 = Employee(102,"Nakul",59000);
e1.display();
e2.display();
return 0;
}

Output
101 Sonoo 890000
102 Nakul 59000
Pointer to Derived Class

1. We know that pointers are used for an object of derived classes, we


can also use them for the base objects. The pointer to the base
class object is type-compatible (can be used in two ways) with a pointer to
the object of the derived class.

2. To access the variable of the base class, a base class pointer will be
used. So, a pointer is a type of base class, and it can access all,
public function and variables of the base class since the pointer is
of the base class, this is known as a binding pointer.
Class B
{
---
---
};
Class D : Public B
{
----
----
};
B *cptr; // here is pointer to class B type variable
B b; // base object
D d; // derived object
cptr=&b; // cptr points to object b
we can make in the above example cptr to point to the object d as
follows
cptr=&d; // cptr points to object d
This is perfectly valid with C++ language because d is an object derived
from the class B
However these is a problem in using cptr to access the public of the
derived class D. using cptr we can access only those members which are
inherited from B and not the member that originally belongs to D. in case a
member of D class has the same name as one of the members of class B,
then any reference to that member by cptr variable will always access the
base class member.
Pointer to Derived Class Program

#include<iostream>
using namespace std;
class BC
{
public:
int b;
void show()
{
cout << "b = : " << b << "\n";
}
};
class DC: public BC
{
public:
int d;
void show()
{
cout << "b = : " << b << "\n";
cout << "d = : " << d << "\n";
}
};
Pointer to Derived Class Program

int main()
{
BC *bptr; // base pointer
BC base;
bptr = &base; //base address
bptr->b = 100; // access BC via base pointer
cout << "bptr points to base object \n";
bptr->show();

DC derived; //derived class


bptr = &derived; // address of derived object
bptr->b = 200; // access DC via base pointer
/* bptr->d = 300; */ // won't work
cout << "bptr now points to derived object \n";
bptr->show(); //bptr now points to derived object
/* accessing d using a pointer of type derived class DC*/
DC *dptr; // derived type pointer
dptr = &derived;
dptr->d = 300;
cout << "dptr is derived type pointer \n";
dptr->show();
cout << "using ((DC*)bptr)\n";
((DC*)bptr)->d = 400;
((DC*)bptr)->show();
}
Output

bptr points to base object


b = : 100
bptr now points to derived object
b = : 200
dptr is derived type pointer
b = : 200
d = : 300
using ((DC*)bptr)
b = : 200
d = : 400
Note: we have used the statement
bptr->show();
so two times first when bptr points to the base object, and second
when bptr is made to point to the derived object. but both the times, it
executed BC::show() function and displayed the content of the base
object.
How ever the statements
dptr->show();
((DC *)bptr)->show(); // cast bptr to DC type
Display the contents of the derived object. This shows that, although a
base pointer can be made to point to any number of derived objects, it
cannot directly access the members defined by a derived class.
Virtual Function

A virtual function is a member function which is declared within a base


class and is re-defined (overridden) by a derived class.
When you refer to a derived class object using a pointer or a reference
to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.

Purpose and Characteristics of Virtual Function

❖ Virtual functions ensure that the correct function is called for an


object,
regardless of the type of reference (or pointer) used for function call.
❖ They are mainly used to achieve Runtime polymorphism
❖ Functions are declared with a virtual keyword in base class.
❖ The resolving of function call is done at runtime.
Rules for Virtual Functions
❖ Virtual functions must be members of some class.
❖ Virtual functions cannot be static members.
❖ They are accessed through object pointers.
❖ They can be a friend of another class.
❖ A virtual function must be defined in the base class, even though it is
not used.
❖ The prototypes of a virtual function of the base class and all the derived
classes must be identical. If the two functions with the same name but
different prototypes, C++ will consider them as the overloaded functions.
❖ We cannot have a virtual constructor, but we can have a virtual destructor
Example Program
#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout << "Printed from Base Class print() Function" << endl;
}
};
class Derived : public Base
{
public:
void print()
{
cout << "Printed from derived Class print() Function" << endl;
}
};
int main()
{
Derived derived1;
// pointer of Base type that points to derived1
Base* base1 = &derived1;
// calls member function of Derived class
// virtual function bined at run time
base1->print();
return 0;
}

Output
Printed from derived Class print() Function

Virtual Function Here, we have declared the print() function of Base as


virtual. So, this function is overridden even when we use a pointer of
Base type that points to the Derived object derived1.
Runtime polymorphism is achieved only through a pointer (or
reference) of base class type. Also, a base class pointer can point to the
objects of base class as well as to the objects of derived class. In above
code, base class pointer ‘base1’ contains the address of object ‘derived1’
of derived class.
Pure Virtual Function

Pure virtual Functions are virtual functions with no definition. They start
with virtual keyword and ends with = 0. Here is the syntax for a pure
virtual function,

Syntax 1
virtual void functionname() = 0;
Note: The = 0 syntax doesn't mean we are assigning 0 to the function. It's
just the way we define pure virtual functions.

Syntax 2
virtual void functionname() {}
Pure virtual functions are used
❖ if a function doesn't have any use in the base class
❖ but the function must be implemented by all its derived classes
Suppose, we have derived Triangle, Square and Circle classes from the
Shape class, and we want to calculate the area of all these shapes. In this
case, we can create a pure virtual function named calculateArea() in the
Shape. Since it's a pure virtual function, all derived classes Triangle,
Square and Circle must include the calculateArea() function with
implementation. A pure virtual function doesn't have the function body
and it must end with = 0.
For example,
class Shape
{
public:
// creating a pure virtual function
virtual void calculateArea() = 0;
};
Example Program
#include <iostream>
using namespace std;
class Shape // Abstract class
{
protected:
float dimension;
public:
void getDimension()
{
cin >> dimension;
}
virtual float calculateArea() = 0; // Pure Virtual Function
};
class Square : public Shape // Derived class
{
public:
float calculateArea()
{
return dimension * dimension;
}
};

class Circle : public Shape // Derived class


{
public:
float calculateArea()
{
return 3.14 * dimension * dimension;
}
};
int main()
{
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;
}
Output
Enter the length of the square: 10
Area of square: 100
Enter radius of the circle: 30
Area of circle: 2826
Characteristics of Pure Virtual Function
1. A pure virtual function is a "do nothing" function. Here "do nothing"
means that it just provides the template, and derived class implements the
function.
2. It can be considered as an empty function means that the pure virtual
function does not have any definition relative to the base class.
3. Programmers need to redefine the pure virtual function in the derived
class as it has no definition in the base class.
4. A class having pure virtual function cannot be used to create direct
objects of its own. It means that the class is containing any pure virtual
function then we cannot create the object of that class. This type of class is
known as an abstract class.
Polymorphism

Polymorphism is an important concept of object-oriented programming.


The term "Polymorphism" is the combination of "poly" + "morphs"
which means many forms. It is a greek word. That is, the same entity
(function or operator) behaves differently in different scenarios.
The + operator in C++ is used to perform two specific functions. When
it is used with numbers (integers and floating-point numbers), it
performs addition.
int a = 5;
int b = 6;
int sum = a + b; // sum = 11
And when we use the + operator with strings, it performs string
concatenation. For example,
string firstName = “R.M.K. ";
string lastName = “Engineering College";
string name = firstName + lastName; // R.M.K. Engineering College
Types of Polymorphism

1. Compile-time Polymorphism.
2. Runtime Polymorphism.
Function overloading - Compile Time Polymorphism

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.
#include <iostream>
using namespace std;
int sum(int num1, int num2) // Function with 2 int parameters
{
return num1 + num2;
}
double sum(double num1, double num2) // unction with 2 double parameters
{
return num1 + num2;
}
int sum(int num1, int num2, int num3) // Function with 3 int parameters
{
return num1 + num2 + num3;
}
int main()
{
// Call function with 2 int parameters
cout << "Sum of Two Integers using sum() = " << sum(5, 6) << endl;
// Call function with 2 double parameters
cout << "Sum of Two Double using sum() = " << sum(5.5, 6.6) << endl;
// Call function with 3 int parameters
cout << "Sum of Three Integers using sum() = " << sum(5, 6, 7) <<
endl;
return 0;
}

Output
Sum of Two Integers using sum() = 11
Sum of Two Double using sum() = 12.1
Sum of Three Integers using sum() = 18
Operator overloading - Compile Time Polymorphism

we can overload an operator as long as we are operating on user-defined


types like objects or structures. We cannot use operator overloading for
basic types such as int, double, etc. Operator overloading is basically
function overloading, where different operator functions have the same
symbol but different operands. And, depending on the operands, different
operator functions are executed.
Program
##include <iostream>
using namespace std;
class Count
{
private:
int number;
public:
Count()
{
number = 5; // Constructor to initialize count to 5
}
void operator ++() // Overload ++ when used as prefix
{
number = number + 1;
}
void display()
{
cout << "Incremented value of member \"number\"
of object Count using overloaded operator ++ is : " << number << endl;
}};
int main()
{
Count count1;
++count1; // Call the "void operator ++()" function
count1.display();
return 0;
}

Output
Incremented value of member "number" of object Count
using overloaded operator ++ is : 6
Virtual Functions - Runtime Polymorphism

A virtual function is a function in a base class that is declared using the


keyword virtual. Defining in a base class a virtual function, with another
version in a derived class, signals to the compiler that we don't want static
linkage for this function. What we want is the selection of the function to
be called at any given point in the program to be based on the kind of
object for which it is called. This sort of operation is referred to as
dynamic linkage, or late binding. Pure Virtual Functions - Runtime
Polymorphism It is possible that you want to include a virtual function in a
base class so that it may be redefined in a derived class to suit the objects
of that class, but that there is no meaningful definition you could give for
the function in the base class.
We can change the virtual function area() in the base class to the following
− virtual function area() = 0
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.
Program
#include <iostream>
using namespace std;
class Shape
{
protected:
int width, height;
public:
Shape( int a = 0, int b = 0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" << width * height << endl;
return width * height;
}
};
class Rectangle: public Shape
{
public:
Rectangle( int a = 0, int b = 0)
{
width = a;
height = b;
}
int area ()
{
cout << "Rectangle class area : " << width * height << endl;
return (width * height);
}
};
class Triangle: public Shape
{
public:
Triangle( int a = 0, int b = 0)
{
width = a;
height = b;
}
int area ()
{
cout << "Triangle class area : " << (width * height)/2 << endl;
return (width * height / 2);
}
};
int main()
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec; // store the address of Rectangle
shape->area(); // call rectangle area.
shape = &tri; // store the address of Triangle
shape->area(); // call triangle area.
return 0;
}

Output
Rectangle class area : 70
Triangle class area : 25
THANK YOU

You might also like