0% found this document useful (0 votes)
14 views30 pages

Multiple Inheritance

C++ coding

Uploaded by

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

Multiple Inheritance

C++ coding

Uploaded by

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

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: Spring 24-25


Lecturer: Md. Faruk Abdullah Al Sohan; [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
using namespace std; class object With virtual functions in
class Base{
base classes.
int b;
public:
Base(int int main(){
b=0):b(b Base *basePtr;
void){}virtual show() {
from baseclass, b
cout <<"from baseclass, b = " <<b<<endl; }
};
Base base(10); = 10 from derived
Derived derived(20); class.. from
class Derived : public Base{ baseclass, b = 0
int d; basePtr = &base; in derived class, d
basePtr- = 20
public:
De
>show();
rive
void show() { basePtr = &derived;
d(intcout << "from derived class.."<<endl; basePtr->show();
d=0)Base::show(); }
:d(d)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 = " pb = & bb;
<<b<<endl; 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 B refers to the object of D (Dynamic


of
Binding)
b = 0
d = 10
Pointer D refers to the object of D
of b =
0
d = 10
Pointer B refers to the object of D after casting
of 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.
PURE VIRTUAL FUN CTIO N & ABSTRACT CLASS

 A class / Base class with only definitions of a virtual function 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().
This is derived1's vfunc().
public: base *p, b; 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
class derived1 : public base { vfunc()
public:
void vfunc() { // point to derived1
cout << "This is derived1's vfunc().\n"; } p = &d1;
}; p->vfunc(); //
access
class derived2 : public base { derived1's
public: vfunc()
// vfunc() not overridden by derived2, base's is
used // point to
}; derived2
p = &d2;
p->vfunc(); //
use base's
vfunc()
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
/* Note: sum() is not a member function of
#include <iostream> 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 int getArea(){ cout << rectangle.getArea() ;
Rectangle; return length *
// declaring breadth; } return 0;
Rectangle as }
friend class void shape( Square a ){
int side; length = a.side; Output:
public: breadth = a.side;} 25
Square };
( int s){

side = s; }
};
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()
class B x = 4; {
{ } A a;
public: friend void B::display(A); B b;
void display(A }; b.display(a);
obj); //no body return 0;
declared }
};
Dynamic Memory Allocation
qC++ provides two dynamic allocation operators: new and delete. The new
operator allocates memory, and the starting address is pointed with a pointer that
returns 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;
}
Dynamic Memory Allocation: Example
1 // new, delete # of elements: 5 *ptr n Sum i
2 int main(){ Enter elements:
3 int n, i,*ptr, sum=0; 2 5 19
0
15
2
8
22 1
4
3
2
50
4 cout << "# of elements: "; 6
5 cin >> n; //input 5 7
6 ptr = new int[n]; 4 0 1 2 3 4
7 if(ptr==NULL){ //ptr==0 3
8 cout << "Error! not Sum = 22 2 6 7 4 3
9 allocated.";
10 return 1;
11 }
12 cout << "Enter elements:\n";
13 for(i=0;i<n;++i)
14 { //input 2 6 7 4 3
15 cin >> *(ptr+i); //ptr[i]
16 sum += *(ptr+i);
17 }
18 cout << "Sum = " << sum;
19 delete [] (ptr);
20 //memory de-allocated
}
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