0% found this document useful (0 votes)
84 views49 pages

Fundamentals of Electrical Drives GK Dubey

This document discusses pointers, virtual functions, and polymorphism in C++. It covers pointers to objects and derived classes, the this pointer, and introduces virtual functions. Key points include: 1. Polymorphism allows one interface with multiple implementations through inheritance and virtual functions. 2. Pointers can point to objects and derived class objects. The this pointer refers to the object invoking a member function. 3. Virtual functions implement runtime polymorphism through dynamic binding based on the actual object type. This allows calling the correct overridden function.

Uploaded by

Stalan Prince
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)
84 views49 pages

Fundamentals of Electrical Drives GK Dubey

This document discusses pointers, virtual functions, and polymorphism in C++. It covers pointers to objects and derived classes, the this pointer, and introduces virtual functions. Key points include: 1. Polymorphism allows one interface with multiple implementations through inheritance and virtual functions. 2. Pointers can point to objects and derived class objects. The this pointer refers to the object invoking a member function. 3. Virtual functions implement runtime polymorphism through dynamic binding based on the actual object type. This allows calling the correct overridden function.

Uploaded by

Stalan Prince
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/ 49

CHAPTER 05:

POINTERS, VIRTUAL FUNCTIONS AND


POLYMORPHISM
Objectives
1. Polymorphism in C++
2. Pointers, this pointer
3. Pointers to derived classes
4. Introduction to virtual functions
5. Pure virtual functions

1
1. POLYMORPHISM
1. One of the crucial features of OOP, 'one name,
multiple forms'.
2. The overloaded member functions are 'selected' for
invoking by matching arguments, both type and
number.
3. This information is known to the compiler at the
compile time.
4. Compiler selects appropriate function for
particular call at the compile time itself.
5. This is called early binding or static binding or
static linking.
EXAMPLE
class A
{
int x;
public: void show( ) { . . . . }
}
class B: public A
{
int y;
public: void show( ) { . . . . }
}

function show( ) should print the values of objects of both


the classes A and B? - scope resolution operator.
It would be nice if the appropriate member function could
be selected while the program is running.
POLYMORPHISM IN C++
2 types
 Compile time polymorphism
 Uses static or early binding
 Example: Function and operator overloading

 Run time polymorphism


 Uses dynamic or late binding
 Example: Virtual functions

4
POLYMORPHISM IN C++

5
2. POINTERS
2.1 Similar to C
a) Declaration of Pointers.
b) Manipulation of Pointers.
c) Pointer Arithmetic.
2.2 Pointer to objects
2.3 this pointer
2.2 POINTER TO OBJECTS
Consider the following statement:
item x;
define a pointer it_ptr of type item as follows:
item *it_ptr;
Store address
it_ptr=&x;

Object pointers are useful in creating objects in run


time.
2.2 POINTER TO OBJECTS

Let us declare an item variable at and a pointer ptr


as follows:
We can refer to the member functions of item in two
ways

or
1. Write a C++ program to create a class for bank
account with members – customer name, contact
number, adhaar number, account number, account
type, balance, ifsc code, branch address. Store
details for one customer by creating a pointer to
object. Display details through same pointer created.

2. Create a pointer to store address of two objects for


customers and display both customer details.
3. Perform the following:
1. Find customer with highest balance in account
2. Display customers having account in same branch
3. Credit interest every month at 4% interest rate for the
customers who maintain minimum Rs. 1000/- average
balance in their account.
4. Debit the fine every month for the customers whose
account balance is less than Rs. 1000/- . Fine to be
imposed is Rs. 50/-.
2.3 THIS POINTER
1. a unique keyword called this to represent an
object that invokes member function.
2. Function call A.max( ) - set pointer this to the
addrees of the object A.

In function,
a=123;
or
this->a=123;
THIS POINTER - EXAMPLE
3. Write a C++ program to create a class person –
name, dob, age, contact. Create two objects A and B
for class person. Store and display details. Find
person who has more age.
3. POINTERS TO DERIVED CLASSES
1. C++ allows base class pointers to point to
derived class objects.
2. Let we have –
class base { … };
class derived : public base { … };
3. Then we can write –
base *p1;
derived d_obj;
p1 = &d_obj;
base *p2 = new derived;

16
3. POINTERS TO DERIVED CLASSES

17
3. POINTERS TO DERIVED CLASSES (CONTD.)

1. Using a base class pointer (pointing to a derived


class object) we can access only those members of
the derived object that were inherited from the
base.
2. This is because the base pointer has knowledge
only of the base class.
3. It knows nothing about the members added by the
derived class.

18
3. POINTERS TO DERIVED CLASSES (CONTD.)
class base { void main( ) {
public: base b1;
void show() { b1.show(); // base
cout << “base\n”; derived d1;
} d1.show(); // derived
}; base *pb = &b1;
class derived : public base { pb->show(); // base
public: pb = &d1;
void show() {
pb->show(); // base
cout << “derived\n”;
}
}
};
All the function calls here
are statically bound
19
3. POINTERS TO DERIVED CLASSES (CONTD.)
1. While it is permissible for a base class pointer to
point to a derived object, the reverse is not true.
base b1;
derived *pd = &b1; // compiler error

2. We can perform a downcast with the help of


type-casting, but should use it with caution (see
next slide).

20
3. POINTERS TO DERIVED CLASSES (CONTD.)
 Let we have –
 class base { … };
 class derived : public base { … };
 class xyz { … }; // having no relation with “base” or
“derived”
 Then if we write –
 base b_obj; base *pb; derived d_obj; pb = &d_obj; //
ok
 derived *pd = pb; // compiler error
 derived *pd = (derived *)pb; // ok, valid downcasting
 xyz obj; // ok
 pd = (derived *)&obj; // invalid casting, no compiler
error, but may cause run-time error
 pd = (derived *)&b_obj; // invalid casting, no 21
compiler error, but may cause run-time error
3. POINTERS TO DERIVED CLASSES (CONTD.)
 In
fact using type-casting, we can use pointer of
any class to point to an object of any other class.
 The compiler will not complain.
 During run-time, the address assignment will also
succeed.
 But if we use the pointer to access any member, then it
may cause run-time error.
 Javaprevents such problems by throwing
“ClassCastException” in case of invalid casting.

22
POINTERS TO DERIVED CLASSES
(CONTD.)

 Pointer arithmetic is relative to the data type


the pointer is declared as pointing to.
 If we point a base pointer to a derived object
and then increment the pointer, it will not be
pointing to the next derived object.
 It will be pointing to (what it thinks is) the
next base object !!!
 Be careful about this.
23
IMPORTANT POINT ON INHERITANCE

 In C++, only public inheritance supports the perfect IS-A


relationship.
 In case of private and protected inheritance, we cannot treat a
derived class object in the same way as a base class object
 Public members of the base class becomes private or protected in the
derived class and hence cannot be accessed directly by others using
derived class objects
 If we use private or protected inheritance, we cannot assign the
address of a derived class object to a base class pointer directly.
 We can use type-casting, but it makes the program logic and
structure complicated.
 This is one of the reason for which Java only supports public
inheritance.

24
INTRODUCTION TO VIRTUAL FUNCTIONS
A virtual function is a member function
that is declared within a base class and
redefined (called overriding) by a derived
class.
 It implements the “one interface, multiple
methods” philosophy that underlies
polymorphism.
 The keyword virtual is used to designate
a member function as virtual.
 Supports run-time polymorphism with the
help of base class pointers.
25
INTRODUCTION TO VIRTUAL
FUNCTIONS (CONTD.)
 While redefining a virtual function in a derived
class, the function signature must match the
original function present in the base class.
 So, we call it overriding, not overloading.
 When a virtual function is redefined by a derived
class, the keyword virtual is not needed (but can
be specified if the programmer wants).
 The “virtual”-ity of the member function
continues along the inheritance chain.
 A class that contains a virtual function is
referred to as a polymorphic class.

26
INTRODUCTION TO VIRTUAL
FUNCTIONS (CONTD.)

 class base {  void main() {


 public:  base b1;
b1.show(); // base - (s.b.)
 virtual void show() { 
 derived d1;
 cout << “base\n”;
 d1.show(); // derived – (s.b.)
 }  base *pb = &b1;
 };  pb->show(); // base - (d.b.)
 class derived : public base {  pb = &d1;
 public:  pb->show(); // derived
 void show() { (d.b.)
 cout << “derived\n”;  }
 Here,
 }
 s.b. = static binding
 };  d.b. = dynamic binding
27
INTRODUCTION TO VIRTUAL
FUNCTIONS (CONTD.)

 class base {  class d2 : public base {


 public:  public:
 virtual void show() {  void show() {
 cout << “derived-2\n”;
 cout << “base\n”;  }
 }  };
 };  void main() {
 class d1 : public base {  base *pb; d1 od1; d2 od2;
 public:  int n;
 void show() {  cin >> n;
 cout << “derived-1\n”;  if (n % 2) pb = &od1;
 }  else pb = &od2;
 };  pb->show(); // guess what ??
 } 28
Run-time polymorphism
VIRTUAL DESTRUCTORS
 Constructors cannot be virtual, but destructors
can be virtual.
 It ensures that the derived class destructor is
called when a base class pointer is used while
deleting a dynamically created derived class
object.

29
VIRTUAL DESTRUCTORS (CONTD.)

 class base {  void main() {


 public:  base *p = new derived;
 ~base() {  delete p;
 cout << “destructing base\n”;  }
 }
 };  Output:
 class derived : public base {  destructing base
 public:
 ~derived() {
 cout << “destructing derived\n”;
 }
 };

30
Using non-virtual destructor
VIRTUAL DESTRUCTORS (CONTD.)

 class base {  void main() {


 public:  base *p = new derived;
 virtual ~base() {  delete p;
 cout << “destructing base\n”;  }
 }
 };  Output:
 class derived : public base {  destructing derived
 public:  destructing base
 ~derived() {
 cout << “destructing derived\n”;
 }
 };

31
Using virtual destructor
MORE ABOUT VIRTUAL FUNCTIONS
 Ifwe want to omit the body of a virtual
function in a base class, we can use pure
virtual functions.
 virtual ret-type func-name(param-list) = 0;
 It makes a class an abstract class.
 We cannot create any objects of such classes.
 It forces derived classes to override it.
 Otherwise they become abstract too.

32
MORE ABOUT VIRTUAL FUNCTIONS
(CONTD.)
 Pure virtual function
 Helps to guarantee that a derived class will
provide its own redefinition.
 We can still create a pointer to an abstract
class
 Because it is at the heart of run-time
polymorphism
 When a virtual function is inherited, so is
its virtual nature.
 We can continue to override virtual
functions along the inheritance hierarchy. 33
APPLYING POLYMORPHISM
 Early binding
 Normal functions, overloaded functions
 Nonvirtual member and friend functions
 Resolved at compile time
 Very efficient
 But lacks flexibility
 Late binding
 Virtual functions accessed via a base class pointer
 Resolved at run-time
 Quite flexible during run-time
 But has run-time overhead; slows down program
execution
34
CHAPTER - 6
EXCEPTIONS
EXCEPTION
 An exception is a unusual, often unpredictable event,
detectable by software or hardware, that requires
special processing occurring at runtime.
 Types of Errors
1. Logical Errors – poor understanding of problem.
2. Syntax errors – poor understanding of language.
3. Exceptions – runtime anomalies or unusual conditions that
program encounters during execution.
 Added by ANSI C++
HANDLING EXCEPTION
• If without handling,
• Program crashes

• Falls into unknown state

• An exception handler is a section of program code


that is designed to execute when a particular
exception occurs
• Resolve the exception

• Lead to known state, such as exiting the program.


BASICS OF HANDLING EXCEPTION
Two kinds:
1. Synchronous exceptions – under control of program: out of range
index, overflow.
2. Asynchronous exceptions – events beyond control: keyboard
interrupts.

C++ is designed to handle Synchronous exceptions.

Mechanism:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (throw the exception)
3. Receive the error information (catch the exception)
4. Take corrective actions (handle the exception)
EXCEPTION HANDLING MECHANISM
EXCEPTION HANDLING MECHANISM
TRY BLOCK THROWING AN EXCEPTION
int main()
{
int a,b; cout<<“enter the values of a and b :”;
cin>>a;
cin>>b;
int x = a-b;
try {
if(x != 0)
{
cout<<“Result (a/x) =“ << a/x;
}
else
{
throw(x);
}
}
catch (int i)
{
cout<<“Exception Caught : x = “ << x << “n”;
}
return 0;
}
EXCEPTIONS THROWN BY FUNCTIONS
Mostly exceptions are thrown by functions that are invoked from
within the try blocks.
The point at which the throw is executed is called the throw point.
EXCEPTIONS THROWN BY FUNCTIONS
void divide(int x, int y, int z)
{
if((x-y) != 0)
{
int r = z/(x-y);
cout << “Result = “ << r << “n”;
}
else
throw (x-y);
}
int main( )
{
try
{
divide(10,20,30);
divide(10,10,20);
}
catch ( int i)
cout << “n Exception caught” ;
return 0;
}
1. Write a C++ program to read a string from
user. Handle the exception if user enters
number.

2. Write a C++ program to read a number from


user. Handle the exception if user enters
character.

3. Write a C++ program to perform arithmetic


operations. Handle exception for divide by
zero error.
MULTIPLE CATCH STATEMENTS
MULTIPLE CATCH STATEMENTS

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