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

PL2 Lecture 8.3-Multiple Inheritance

The document covers principles of object-oriented programming, focusing on virtual functions, polymorphism, and abstract classes in C++. It explains how virtual functions allow derived classes to redefine base class functions, enabling dynamic binding at runtime. Additionally, it discusses pure virtual functions and abstract classes, which cannot be instantiated but can be referenced, facilitating polymorphism in C++.

Uploaded by

srabonisheikh14
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 views29 pages

PL2 Lecture 8.3-Multiple Inheritance

The document covers principles of object-oriented programming, focusing on virtual functions, polymorphism, and abstract classes in C++. It explains how virtual functions allow derived classes to redefine base class functions, enabling dynamic binding at runtime. Additionally, it discusses pure virtual functions and abstract classes, which cannot be instantiated but can be referenced, facilitating polymorphism in C++.

Uploaded by

srabonisheikh14
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/ 29

Principles of object-oriented

programming
Course Code: CSC 2213 Course Title: Programming Language 2

Dept. of Computer Science


Faculty of Science and Technology

Lecturer No: 8 Week No: 9 Semester: Fall 23-24


Lecturer: Sirajum Munira Shifat; [email protected]
Virtual Functions

 A virtual function is a member function that is declared within a base class


and redefined by a derived class. To create a virtual function, precede the
function's declaration in the base class with the keyword virtual.
 When a class containing a virtual function is inherited, the derived class
redefines the virtual function to fit its own needs.
Virtual Functions

 A base-class pointer can be used to point to an object of any class derived


from that base.
 When a base pointer points to a derived object that contains a virtual
function, C++ determines which version of that function to call based upon
the type of object pointed to by the pointer. And this determination is
made at run time.
 Thus, when different objects are pointed to, different versions of the virtual
function are executed.
VIRTUAL FUNCTION

In case of base class pointer object, if the base class function is declared as virtual

Then C++ can determine in runtime which function to call (from base class or from derived
class) based on the object pointed by the base class pointer.

• The function in the base class is declared as virtual by using the keyword virtual preceding its
normal declaration.
#include<iostream> Base class pointer pointing to derived class object
using namespace std; With virtual functions in base classes.
class Base{
int b;
public:
Base(int b=0):b(b){} int main(){
Base *basePtr;
void virtual show() { from baseclass,b = 10
cout <<"from baseclass, b = " <<b<<endl; }
};
Base base(10); from derived class..
Derived derived(20); from baseclass,b = 0
class Derived : public Base{ in derived class,d = 20
int d; basePtr = &base;
public: basePtr->show();
Derived(int d=0):d(d){}

void show() { basePtr = &derived;


cout << "from derived class.."<<endl; basePtr->show();
Base::show(); }
cout << "in derived class, d = "<<d<<endl;
}
};
Check yourself!!

class B
{
int b;
int main()
{
public: B *pb;
B(int b=0):b(b){} B bb(5);
virtual void show()
cout << "Pointer of B refers to the object of B" << endl;
{
cout <<"b = " <<b<<endl; pb = & bb;
}
pb->show();
}; cout << "Pointer of B refers to the object of D (Dynamic Binding) " << endl;
D dd(10);
pb = &dd;
class D : public B pb->show();
{
int d; cout << "Pointer of D refers to the object of D" << endl;
D *pd;
public: pd = &dd;
D(int d=0):d(d){} pd->show();
void show()
cout << "Pointer of B refers to the object of D after casting" << endl;
{ ((D *)pb)->show();
B::show();
return 0;
cout << "d = "<<d<<endl; }
}
};
Pointer of B refers to the object of B
b = 5

Pointer of B refers to the object of D (Dynamic


Binding)
b = 0
d = 10

Pointer of D refers to the object of D


b = 0
d = 10

Pointer of B refers to the object of D after casting


b = 0
d = 10
POLYMORPHISM
Polymorphism means same action but different reaction/reply.
Or
Same entity having different forms!!
In C++, polymorphism refers to the property by which objects belonging to different classes are
able to respond to the same message, but in different forms.

Polymorphism is also known as late binding/dynamic binding/run-time

binding. In C++, two things are required to achieve polymorphism


1. A virtual function in the base class.
2. A pointer of the base class.
PUREVIRTUAL FUN C TIO N & ABSTRAC T C LASS
 A class / Base class with only definitions in it (i.e., no code implementation) is called abstract
class.

 We cannot create objects of an abstract class.

 Pure virtual function:

 A pure virtual function is used to make a class abstract.

 A virtual function is made ‘pure virtual’ by assigning zero(0) to the function name. Such a
function is also known as ‘do-nothing’ function.

 e.g., virtual void show() = 0;


Pure Virtual Functions

 A pure virtual function is a virtual function that has no definition within the
base class.

 To declare a pure virtual function, use this general form:

 virtual type func-name(parameter-list) = 0;

 When a virtual function is made pure, any derived class must provide its own
definition. If the derived class fails to override the pure virtual function, a
compile- time error will result.
Abstract Classes

 A class that contains at least one pure virtual function is said to be abstract.
Because an abstract class contains one or more functions for which there is no
definition (that is, a pure virtual function), no objects of an abstract class may be
created.

 Although you cannot create objects of an abstract class, you can create pointers
and references to an abstract class. This allows abstract classes to support run-time
polymorphism.
Abstract Classes

class number { class decType : public number { int main(){


protected: public: decType d;
int val; void show() { hexType h;
public: cout << val << "\n"; octType o;
void setval(int i) { val = i; } }
// show() is a pure virtual }; d.setval(20);
function d.show(); // displays 20
virtual void show() = 0; class octType : public number h.setval(20);
}; { h.show(); // displays 14
class hexType : public number { public: o.setval(20);
public: void show() { o.show(); // displays 24
void show() { cout << oct << val << "\n";
cout << hex << val << "\n";} } return 0;
}; }; }
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};

class Derived:public Base


{
public:
void show()
{ cout << "Implementation of Virtual Function in Derived class"; }
};

int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};

class Derived1:public Base {


public:
void show(){ cout << "Implementation of Virtual Function in Derived class 1 \n";}
};

class Derived2:public Base{


public:
void show(){ cout << "Implementation of Virtual Function in Derived class 2"; }
};

int main(){
Base *b;
Derived1 d1;
Derived2 d2;
b = &d1;
b->show();
b = &d2;
b->show();
}
ALL ABOUT VIRTUAL

- Virtual keyword is used with derived class to create only one instance of base class in
case of multiple inheritance.

- Virtual keyword is used with base class function name to implement Polymorphism /
dynamic linking /runtime binding. In polymorphism a pointer object of a base class can
resolve in runtime which function to call based on the actual object its pointing to!

- Pure virtual function is used to declare an abstract base class.


Polymorphism: Early Binding (static )

 Early binding refers to events that occur at compile time.


 Early binding occurs when all information needed to call a function is
known at compile time.
 Examples of early binding include normal function calls, overloaded
function calls, and overloaded operators.
 The main advantage to early binding is efficiency. Because all information
necessary to call a function is determined at compile time; these types of
function calls are very fast.
Polymorphism: Late binding (dynamic)

 The opposite of early binding is late binding. As it relates to C++, late binding
refers to function calls that are not resolved until run time.
 Virtual functions are used to achieve late binding.
 When access is via a base pointer or reference, the virtual function calling is
determined by the type of object pointed to by the pointer.
 The main advantage to late binding is flexibility. Late binding allows to
create programs that can respond to events occurring while the program
executes.
Virtual Functions Are Hierarchical
Output:
class base { int main(){ This is base's vfunc().
public: base *p, b; This is derived1's vfunc().
This is base's vfunc().
derived1 d1;
virtual void vfunc() { derived2 d2;
cout << "This is base's vfunc().\n"; }
}; p = &b;
p->vfunc(); // access base's vfunc()
class derived1 : public base {
public: // point to derived1
void vfunc() { p = &d1;
cout << "This is derived1's vfunc().\n"; } p->vfunc(); // access derived1's vfunc()
};
// point to derived2
class derived2 : public base { p = &d2;
public: p->vfunc(); // use base's vfunc()
// vfunc() not overridden by derived2, base's is
used return 0;
}; }
Friend Function

 It is possible to grant a nonmember function access to the private


members of a class by using a friend.
 A friend function has access to all private and protected members of the
class for which it is a friend.
 Syntax :
 friend function-declaration()
Friend Function: Example
#include <iostream> /* Note: sum() is not a member function of
any class.*/
using namespace std; int sum(myclass x)
{
class myclass { /* Because sum() is a friend of myclass, it
int a, b; public: can directly access a and b. */
friend int sum(myclass x);
return x.a + x.b;
void set_ab(int i, int j) }
{
a = i; b = j; int main()
} {
}; myclass n;
n.set_ab(3, 4);
cout << sum(n);
return 0;
}
Friend Class

Friend class—A class in which all functions can access the non-public members
of another class. The general format of friend class is –

class A
{
class B is declared as a friend of class A . So,
friend class B;
now all the member functions of class B
};
became friend functions of class A.
class B
{

};
Friend Class: Example

#include <iostream> class Rectangle int main()


using namespace std; { {
int length; Square square(5);
class Square int breadth; Rectangle rectangle;
{ public: rectangle.shape(square);
friend class Rectangle; int getArea(){ cout << rectangle.getArea() ;
// declaring Rectangle as return length *
friend class breadth; } return 0;
int side; }
public: void shape( Square a ){
Square ( int s){ length = a.side; Output:
side = s; } breadth = a.side;} 25
}; };
Class Members as Friend

 It is possible to make a function of one class as a friend of another class.

 We do this in the same way as we make a function as a friend of a class. The only
difference is that we need to write class_name :: in the declaration before the
name of that function in the class whose friend it is being declared.

 The friend function is only specified in the class and its entire body is declared
outside the class.
Class Members as Friend: Format
class A; // forward declaration of A
needed by B

class B
{
void display( A a ); //only specified. Body is not declared
};

class A
{
friend void B::display( A );
};

void B::display(A a) //declaration here


{}
Class Members as Friend: Example

#include <iostream> class A void B::display(A obj)


using namespace std; { {
int x; cout << obj.x << endl;
class A; // forward public: }
declaration of A A()
needed by B
{ int main()
x = 4; {
class B
{ } A a;
public: friend void B::display(A); B b;
void display(A obj); }; b.display(a);
//no body declared return 0;
}; }
Dynamic Memory Allocation
 C++ provides two dynamic allocation operators: new and delete. The new
operator allocates memory and returns a pointer to the start of it. The delete
operator frees memory previously allocated using new.

The general forms of new and delete are shown here:

 p_var = new type;

 delete p_var;

 Here, p_var is a pointer variable that receives a pointer to memory that is large
enough to hold an item of type type.
Dynamic Memory Allocation: Example

#include <iostream>
using namespace std;
int main()
{
int *p;
p = new int; // allocate memory for int
*p = 20; // assign that memory the value 20
cout << *p; // prove that it works by displaying value
delete p; // free the memory

return 0;
}
References
1. https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm
2. https://www.cplusplus.com/doc/tutorial/
3. http://en.cppreference.com/w/cpp/header
Books
 Teach Yourself C++, 3rd Edition, Herbert Schildt.

 The C++ Complete Reference, 4th Edition, Herbert Schildt.

 C++ How to Program, 4th Edition, Deitel and Deitel.

 The C++ Programming Language, Special 3rd Edition, Bjarne Stroustrup

 Thinking in C++, Volume One, 2nd Edition. Bruce Eckel.

You might also like