You are on page 1of 73

Week 11-12-13-14

Outline
• Operators and its types
• Operators Overloading
• Unary operators Overloading
• Binary operators Overloading
• Introduction to Inheritance
• Types of inheritance
• Introduction to Polymorphism
• Virtual and Pure Virtual Functions
• Abstract Base classes and Concrete derived classes

1
Operators and its types
• Assignment (=)
• The assignment operator assigns a value to a variable. a =
5;
• This statement assigns the integer value 5 to the variable a.
The part at the left of the assignment operator (=) is known
as the lvalue (left value) and the right one as the rvalue
(right value). The lvalue has to be a variable whereas the
rvalue can be either a constant, a variable, the result of an
operation or any combination of these.
The most important rule when assigning is the right-to-left
rule: The assignment operation always takes place from
right to left, and never the other way:
a = b;
Operators and its types
(con’t)
• Arithmetic operators ( +, -, *, /, % )
• The five arithmetical operations supported by the C++ language
are: + (addition),
- (subtraction), * (multiplication), /(division), %(modulo)
• Operations of addition, subtraction, multiplication and division
literally correspond with their respective mathematical operators.
The only one that you might not be so used to see may be
modulo; whose operator is the percentage sign (%). Modulo is the
operation that gives the remainder of a division of two values. For
example, if we write:
• a = 11 % 3; the variable a will contain the value 2, since 2 is the
remainder from dividing 11 between 3.
• Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=,
^=, |=)
• When we want to modify the value of a variable by performing an
operation on the value currently stored in that variable we can use
compound assignment operators:
Expression is Equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
Operators and its types
(con’t)
• Increase and decrease (++, --)
• Shortening even more some expressions, the increase
operator (++) and the decrease operator (--) increase or
reduce by one the value stored in a variable. They are
equivalent to +=1 and to -=1, respectively.
• Thus: c++; c+=1; c=c+1; are all equivalent in its
functionality: the three of them increase by one the value
of c.
• For example:
• Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B
contains 4
Operators and its types
(con’t)
• Relational and equality operators ( ==, !=, >, <, >=,
<=)
• In order to evaluate a comparison between two expressions
we can use the relational and equality operators. The result
of a relational operation is a Boolean value that can only be
true or false, according to its Boolean result.
• We may want to compare two expressions, for example, to
know if they are equal or if one is greater than the other is.
Here is a list of the relational and equality operators that
can be used in C++:
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
Operators and its types
(con’t)
• Logical operators ( !, &&, || )
• The Operator ! is the C++ operator
to perform the Boolean operation
NOT, it has only one operand,
located at its right, and the only
thing that it does is to inverse the
value of it, producing false if its
operand is true and true if its
operand is false. Basically, it returns
the opposite Boolean value of
evaluating its operand.
Operators and its types
(con’t)
• Conditional operator ( ? )
• The conditional operator evaluates an expression
returning a value if that expression is true and a
different one if the expression is evaluated as
false. Its format is:
condition ? result1 : result2

• If condition is true the expression will return


result1, if it is not it will return result2.
• 7==5 ? 4 : 3 // returns 3, since 7 is not
equal to 5. 7==5+2 ? 4 : 3 // returns 4,
since 7 is equal to 5+2. 5>3 ? a : b //
returns the value of a, since 5 is greater
than 3. a>b ? a : b // returns whichever is
//greater, a or b.
Operators and its types
(con’t)
• Comma operator ( , )
• The comma operator (,) is used to separate two or more
expressions that are included where only one expression is
expected. When the set of expressions has to be evaluated for a
value, only the rightmost expression is considered. For example,
the following code:
• a = (b=3, b+2); Would first assign the value 3 to b, and then
assign b+2 to variable a. So, at the end, variable a would contain
the value 5 while variable b would contain value 3.
• Bitwise Operators ( &, |, ^, ~, <<, >> )
• Bitwise operators modify variables considering the bit patterns
that represent the values they store.
• Operator Asm equivalent Description
& AND Bitwise AND
| OR Bitwise
Inclusive OR
^ XOR Bitwise Exclusive OR
~ NOT Unary complement (bit
inversion)
<< SHL Shift Left
>> SHR Shift Right
Operators and its types
(con’t)
• sizeof()
• This operator accepts one parameter,
which can be either a type or a variable
itself and returns the size in bytes of that
type or object:
a = sizeof (char);
• This will assign the value 1 to a because
char is a one-byte long type.
• The value returned by sizeof is a constant,
so it is always determined before program
execution.
Operators overloading
• The general syntax for defining an
operator overloading is as follows:
return_type classname :: operator
operator symbol(argument)
{
…………..
statements;
}
Operators
overloading(con’t)
• Thus the above clearly specifies that operator
overloading is defined as a member function by
making use of the keyword operator.
• In the above:
• return_type – is the data type returned by the
function
• class name - is the name of the class
• operator – is the keyword
• operator symbol – is the symbol of the operator
which is being overloaded or defined for new
functionality
• :: - is the scope resolution operator which is used
to use the function definition outside the class.
Unary operator overloading
• As the name implies takes operate on only one
operand. Some unary operators are namely ++ called
as Increment operator, -- called as Decrement
Operator, ! not ,  ~, unary minus.
• The operator keyword
• The keyword operator is used to overload the operator
“++” for e.g.
void operator ++ ()
• The return types (void in this case) comes first,
followed by the operator itself (++) and finally the
argument list enclosed in the parentheses (which are
empty here)
• The declarator syntax tells compiler to call this
member function whenever the ++ operator is
encountered, provided the operand (the variable
operated on by the ++) is of type class
An example of unary
operator overloading
• 1 // countpp1.cpp
• 2 // increment counter variable with ++ operator
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7
• 8 class Counter
• 9 {
• 10 private:
• 11 unsigned int count; // count
• 12 public:
• 13 Counter() { count=1; } // constructor
• 14 int get_oount() { return count; } // return count
• 15 void operator ++ () { count=count*2; } // increment count
• 16 };
• 17 int main()
• 18 {
• 19 Counter c1,c2; //define and initialize
• 20 cout <<“\nc1= “ <<c1.get_count(); //display
• 21 cout <<“\nc2= “ <<c2.get_count();
• 22 ++c1; //increment c1
• 23 ++c2; //increment c2
• 24 ++c2; //increment c2
• 25 cout << “\nc1=“ <<c1.get_count(); //display again
• 26 cout << “\nc2=“ <<c2.get_count();
• 27 return 0; // indicates successful termination
• 28
• 29 } // end main
c1=1
c2=1
c1=2
c2=4
Unary operators overloading
(con’t)
• In the previous example, we create
two objects of class Counter c1 and
c2
• The counts in the objects are
displayed; they are initially 0. then
using the overloaded ++ operator,
we increment c1 once, and display
the resulting values
Binary operator overloading
• The arithmetic operators (i.e. +,-,*,/)
comparison operators (i.e. <,>,<>)
and arithmetic assignment operators
(i.e. =,!=, ==) operate on two
operands can be overloaded
Binary operator overloading
• 1 // bover1.cpp
• 2 // overload + operator
• 3 #include <iostream.h>
• 4 #include <conio.h>
• 5 class Exforsys
• 6 {
• 7 private:
• 8 int x;
• 9 int y;
• 10 public:
• 11 Exforsys() //Constructor
• 12 { x=0; y=0;}
• 13 Exforsys(int x1, int y1)
• 14 { x=x1; y=y1; }
• 15 void getvalue( ) //Member Function for Inputting Values
• 16 {
• 17 cout << "\n Enter value for x: ";
• 18 cin>> x;
• 19 cout << "\n Enter value for y: ";
• 20 cin>> y;
• 21 }
• 22 void displayvalue( ) //Member Function for Outputting Values
• 23 {
• 24 cout <<"value of x is: " << x;
• 25 cout<< "value of y is: "<<y;
• 26 }
• 27 Exforsys operator + (Exforsys);
• 28 };
• 29 Exforsys Exforsys::operator + (Exforsys e2)
• 30 { int x1 = x* e2.x;
• 31 int y1 = y* e2.y;
• 32 return Exforsys (x1,y1); }
• 33 void main( )
• 34 {
• 35 clrscr();
• 36 Exforsys e1,e2,e3; //Objects e1, e2, e3 created
• 37 cout<<"\nEnter value for Object e1 ";
• 38 e1.getvalue( );
• 39 cout<<"\nEnter value for Object e2 ";
• 40 e2.getvalue( );
• 41 e3= e1 + e2; //Binary Overloaded operator used
• 42 cout<< "\nValue of e1 is:";
• 43 e1.displayvalue();
• 44 cout<< "\nValue of e2 is:";
• 45 e2.displayvalue();
• 46 cout<< "\nValue of e3 is:";
• 47 e3.displayvalue();
• 48 }
Enter value for object e1
Enter value for x:2
Enter value for y:3
Enter value for object e2
Enter value for x:4
Enter value for y:5
value of e1 is:
value of x is:2
value of y is:3
value of e2 is:
value of x is:4
value of y is:5
value of e3 is:
value of x is:6
value of y is:20
Binary operators
overloading (con’t)
• In the previous example, we create three objects of class
Exforsys e1, e2 and e3
• The variables x and y are initialized with 0 in the objects e1
and e2
• The binary overloaded operator ‘+’ is used. In this
statement, the argument on the left side of the operator ‘+’,
e1, is the object of the class Exforsys in which the binary
overloaded operator ‘+’ is a member function
• The right side of the operator ‘+’ is e2. This is passed as an
argument to the operator ‘+’ . Since the object e2 is passed
as argument to the operator’+’ inside the function defined
for binary operator overloading, the values are accessed as
e2.x and e2.y. This is added with e1.x and e1.y, which are
accessed directly as x and y. The return value is of type class
Exforsys as defined by the above example
• we multiply e1 and e2 and store in e3, and display the
Introduction to Inheritance
• In inheritance the code of existing classes
is used for making new classes
• In inheritance a new class is written such
that it can access or use the members of an
existing class is called derived class or child
class
• The existing class is called base class or
parent class
• The derived class can use the data
members and member functions of the
base class
• It can also have its own data members and
member functions, thus making it larger
than base class
Introduction to Inheritance
(con’t)
Member1

Member2
Base class

Member1

Member2

Derived class Member3

• In the figure, the arrow shows that the derived class can access the
members of base class but the base class cannot access members of it
derived class
Categories of inheritance
• Single inheritance
• Multiple inheritance
• In single inheritance, the new class is
derived from only one base class
• In multiple inheritance, the new class
is derived from more than one base
classes
Protected Access Specifier
• Public members of a class are accessible by
all functions in the program
• Private members of a class are accessible
only by member functions and friend
functions of that class
• Protected members of the class are
accessible by the member functions and
friend functions of that class
• Difference b/w protected members and
private members
– The protected members of a base class are,
however, accessible by the members of its
derived classes but
– The private members of the base class are not
accessible directly by members of its derived
General syntax for defining a
derived class
class sub_class_name : specifier base_class_name
{
-----------
members of derived class
-----------
};

where
sub_class_name -> represents name of the derived
class
: (colon) -> sets relation b/w the classes
specifier -> represents the access specifier. It
may be public, private or
protected
base_class_name -> represents name of the base class
Types of inheritance

Single inheritance
Types of inheritance
• Public inheritance
• Private inheritance
• Protected inheritance
Public inheritance
• Public inheritance
– The public members of the base class
become the public members of the
derived class
– Thus the objects of the derived class can
only access public members (data and
functions) of the base class
– The protected members of the base
class also becomes protected members
of derived class or can access protected
data members of the base class
General syntax for deriving a
public class from base class
class sub_class_name : public base_class_name
{
-----------
-----------
-----------
};

where
public -> specifies the public
inheritance
sub_class_name -> represents name of the
derived class
base_class_name -> represents name of the base
class
An example of Public


1
2
inheritance
// public1.cpp
// An example of a public inheritance
• 3 #include <iostream>
• 4
• 5
• 6
• 7 class student
• 9 {
• 10 private:
• 11 char name[15], address[25]; //declare character arrays
• 12 public:
• 13 void input (void)
• 14 { cout<< “Enter Name “;
• 15 cin>>name;
• 16 cout <<“Enter Address “;
• 17 cin>>address;
• 18 }
• 19 void show (void)
• 20 { cout<<“\nName: “<<name<<endl;
• 21 cout<<“Address: “<<address<<endl;
• 22 } };
• 23 class marks: public student
• 24 {
• 25 private:
• 26 int s1,s2,s3,total;
• 27 public:
• 28 void inputmarks (void)
• 29 { cout<<“\nEnter marks of sub1 “; cin>>s1;
• 30 cout<<“Enter marks of sub2 “; cin>>s2;
• 31 cout<<“Enter marks of sub3 “; cin>>s3;
• 32 total= s1+s2+s3;
• 33 } void show_detail (void); };
An example of Public


34
35
inheritance
void main()
{
• 36 marks mmm;
• 37 mmm.input();
• 38 mmm.inputmarks();
• 39 mmm.show();
• 39 mmm.show_detail();
• 40 getch(); }
• 41 void marks :: show_detail() //defining member function “show_detail” outside
the class “marks”
• 42 {
• 43 cout<<“\nMarks of 1st sub: “<<s1<<endl; cout<<“Marks of 2st sub: “<<s2<<endl;
• 44 cout<<“Marks of 3rd sub: “<<s3<<endl;
• 45 cout<<“Total marks :”<<total<<endl;
• 46
• 48 } // end main
Enter Name shehzad
Enter Address hayatabad

Enter marks of sub1 30


Enter marks of sub2 20
Enter marks of sub3 10

Name: shehzad
Address: hayatabad

Marks of 1st sub:30


Marks of 2st sub:20
Marks of 3rd sub:10
Total marks:60
Public inheritance (con’t)
• In the previous example, the class marks
is defined as a derived class
• The keyword “public” and the name of the
base class “student” followed by colon(:)
are written while defining derived class
• This shows that the objects of the derived
class are able to access public members of
the base class. It is called public
inheritance
• The derived class “marks” can access the
“input” and “show” member functions of
the base class, but cannot access other
private members of the base class
Another example of Public


1
2
inheritance
// public2.cpp
// An example of a public inheritance
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7 class A
• 9 {
• 10 private:
• 11 int a1,a2;
• 12 protected:
• 13 int p1,p2;
• 14 public:
• 15 void ppp(void)
• 16 {
• 17 cout<<”Value of p1 of class A= “<<p1<<endl;
• 18 cout<<“Value of p2 of class A= “<<p2<<endl; } };
• 19 class B : public A
• 20 {
• 21 public:
• 22 void get(void)
• 23 {
• 24 cout<<“Enter value of p1 ? ”; cin>>p1; //class B access protected data member p1
• 25 cout<<“Enter value of p2 ? ”; cin>>p2; //class B access protected data member p2
• 26 }
• 27 };
• 28 int main()
• 29 {
• 30 B ob;
• 31 ob.get();
• 32 ob.ppp(); //class B object “obj” access public member function “ppp” of class A
• 33
• 34 return 0; // indicates successful termination
• 35 } // end main
Enter value of p1 ? 2
Enter value of p2 ? 3
Value of p1 of class A=2
Value of p2 of class A=3
Public inheritance (con’t)
• In the previous program, the class
“B” is publicly derived from class “A”
• The objects of the class “B”:
– Cannot access the private data
members “a1” & “a2” of base class “A”
– Can access the public member function
“ppp” of base class “A” using its object
“ob”
– Can access the protected data members
“p1”
& “p2” of base class “A”
Private inheritance
• Private inheritance
– The objects of the derived class cannot
access public members and private
members (data and functions) of the
base class
– It can only access protected members of
the base class
General syntax for deriving a
private class from base class
class sub_class_name : private base_class_name
{
-----------
-----------
-----------
};

where
private -> specifies the private
inheritance
sub_class_name -> represents name of the
derived class
base_class_name -> represents name of the base
class
An example of Private


1
2
inheritance
// private1.cpp
// An example of a private inheritance
• 3 #include <iostream.h>
• 4
• 5
• 6 class A
• 7 {
• 8 private:
• 9 int a1,a2;
• 10 public:
• 11 void ddd() { cout<<“cannot access public member function”; }
• 12 protected:
• 13 int p1,p2;
• 14
• 15 void ppp(void) //protected member function
• 16 {
• 17 cout<<”Value of p1 of class A= “<<p1<<endl;
• 18 cout<<”Value of p2 of class A= “<<p2<<endl; } };
• 19 class B : private A
• 20 {
• 21 public:
• 22 void get(void)
• 23 {
• 24 cout<<“Enter value of p1 ? ”; cin>>p1;
• 25 cout<<“Enter value of p2 ? ”; cin>>p2;
• 26 ppp(); //call protected member function ppp()
• 27 } };
• 28 int main() //ppp() is not acessible in main because it is protected
• 29 {
• 30 B ob;
• 31 ob.get();
• 32 ob.ddd(); //ddd() is not accessiable
• 33 return 0; // indicates successful termination
• 34 } // end main
Enter value of p1 ?2
Enter value of p2 ?3
Value of p1 of class A=2
Value of p2 of class A=3
Private inheritance (con’t)
• In the previous program, the class “B” is
derived as private from the base class “A”
• The objects of the class “B”:
– Cannot access the private data members “a1”
& “a2” of base class “A”
– Cannot access the public member function
“ddd” of base class “A”
– Can access the protected data members “p1”
& “p2” of base class “A”
– Can access the protected member function
“ppp”
of base class “A”
Protected inheritance
• Protected inheritance
– The objects of the derived class that is
derived as protected can access only
the protected members of the base
class
General syntax for deriving a
protected class from base class
class sub_class_name : protected base_class_name
{
-----------
-----------
-----------
};

where
protected -> specifies the protected
inheritance
sub_class_name -> represents name of the
derived class
base_class_name -> represents name of the base
class
An example of Protected


1
2
inheritance
// protected1.cpp
// An example of a protected inheritance
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7 class A
• 9 {
• 10 private:
• 11 int a1,a2;
• 12 protected:
• 13 int p1,p2;
• 14 public:
• 15 void ppp(void)
• 16 {
• 17 cout>>”Value of p1 of class A= “<<p1<<endl;
• 18 cout>>”Value of p2 of class A= “<<p2<<endl; } };
• 19 class B : protected A
• 20 {
• 21 public:
• 22 void get(void)
• 23 {
• 24 cout<<“Enter value of p1 ? ”; cin>>p1;
• 25 cout<<“Enter value of p2 ? ”; cin>>p2;
• 26 cout>>”Value of p1 of class A= “<<p1<<endl;
• 27 cout>>”Value of p2 of class A= “<<p2<<endl; } };
• 28 void main()
• 29 {
• 30 B ob;
• 31 ob.get();
• 32
• 33 return 0; // indicates successful termination
• 34 } // end main
Enter value of p1 ?2
Enter value of p2 ?3
Value of p1 of class A=2
Value of p2 of class A=3
Protected inheritance
(con’t)
• In the previous program, the class
“B” is derived as protected from the
base class “A”
• The objects of the class “B”:
– Can only access the protected data
members “p1” & “p2” of base class “A”
Types of inheritance

Multiple inheritance
Multiple inheritance
(con’t)
• In multiple inheritance, a class is derived
by using more than one classes
• In multiple inheritance, the derived class
receives the members of two or more base
classes
• Multiple inheritance is a powerful feature
of OOP
• This technique reduces the program size
and saves programmer’s time
• The programmer uses the existing base
classes in the program coding to solve
problems
Multiple Inheritance (con’t)
Member1 Member1 Member1
Member2 Member2 Member2

Base class A Base class B Base class C

Member1

Member2

Derived class D Member3

• In the figure, the arrow shows that the Derived class D can access the
members of base class A, B and C respectively, but the base classes
cannot access members of it derived class
General syntax for defining a
derived class from multiple
base classes
class sub_class : specifier base_class1, specifier
base_class2, …
{
-----------
members of derived class
-----------
};

where
sub_class_name -> represents name of the derived
class
: (colon) -> sets relation b/w the classes
specifier base_class1 -> represents the access specifier of
the first base class.
specifier base_class2 -> represents the access specifier of
the second base class.
An example of Multiple


1
2
inheritance
// multiple1.cpp
// An example of a multiple inheritance
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7 class student
• 9 {
• 10 private:
• 11 char name[15], address[15]; //declare character arrays
• 12 public:
• 13 void input (void)
• 14 { cout<< “Enter name: “;
• 15 cin>>name;
• 16 cout <<“Enter Address: “;
• 17 cin>>address;
• 18 }
• 19 void print (void)
• 20 { cout<< “Name: “<<name<<endl;
• 21 cout <<“Address: “<<address<<endl;
• 22 };
• 23 class marks
• 24 {
• 25 private:
• 26 int s1,s2,s3,total;
• 27 public:
• 28 void inputmarks (void)
• 29 { cout<<“Enter marks of sub1: “; cin>>s1;
• 30 cout<<“Enter marks of sub2: “; cin>>s2;
• 31 cout<<“Enter marks of sub3: “; cin>>s3;
• 32 total= s1+s2+s3; }
• 33 void showmarks(void) {
• 34 cout<<“Marks of 1st sub: “<<s1<<endl; cout<<“Marks of 2st sub: “<<s2<<endl;
• 35 cout<<“Marks of 3rd sub: “<<s3<<endl;
• 36 cout<<“Total marks :”<<total<<endl;
• 37 }
• 38 };
• 39 class show : public student, public marks
• 40 {
• 41 public:
• 42 void show_rec(void)
• 43 {
• 44 cout<<“\nThe complete record is ”<<endl;
• 45 cout<<“==========================“<<endl;
• 46
• 47
• 48 }
• 49 };
• 50 int main()
• 51 {
• 52 show mo;
• 53 mo.input();
• 54 mo.inputmarks();
• 55 mo.show_rec();
• 56 mo.print();
• 57 mo.showmarks();
• 58 return 0; // indicates successful termination
• 59 } // end main
Enter name: shehzad
Enter Address: hayatabad
Enter marks of sub1:52
Enter marks of sub2:63
Enter marks of sub3:85

The complete record is


==========================
Name: shehzad
Address: hayatabad
Marks of 1st sub:52
Marks of 2nd sub:63
Marks of 3rd sub:85
Introduction to
Polymorphism
• In polymorphism, the member functions
with the same name are defined in each
derived class and also in the base class
• Polymorphism is used to keep the
interface of base class to its derived
classes
• “Poly” means many and “morphism”
means form
• Polymorphism is achieved by means of
virtual functions
Polymorphism (con’t)
• Pointers to objects
• The members of a class can be accessed through the
pointer to the class
• The arrow (->) symbol is used to access them
• This symbol is also known as member access operator
• The general syntax to access a member of a class
through its pointer is:
p->class member
where
p is the pointer to the object
-> it is the member access
operator. It is used to access
the members of the
object through the pointer
class member it is the member of the object
An example of


1
2
// poly1.cpp
polymorphism
// An example of a polymorphism
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7 class bb
• 8 {
• 9 public:
• 10 void ppp()
• 11 {
• 12 cout<<“It is the base class”<<endl;
• 13 }
• 14 };
• 15 class d1 : public bb
• 16 {
• 17 public:
• 18 void ppp()
• 19 {
• 20 cout<<“It is the first derived class”<<endl;
• 21 }
• 22 };
• 23 class d2 : public bb
• 24 void ppp()
• 25 {
• 26 cout<<“It is the second derived class”<<endl;
• 27 }
• 28 };
• 29 int main()
• 30 {
• 31 bb *p;
• 32 d1 a;
• 33 d2 b;
• 34 p = &a;
• 35 p-> ppp();
• 36 p = &b;
• 37 p-> ppp();
• 38 return 0; // indicates successful termination
• 39 } // end main
It is the base class
It is the base class
Polymorphism (con’t)
• In the previous example, one pointer object “p” of base
class “bb” is declared
• One object “a” of derived class “d1” is declared
• One object “b” of derived class “d2” is declared
• The statement “p=&a” assigns address of object “a” to the
pointer object “p”
• When p->ppp() is executed, the member function of the
base class is executed, since the type of the pointer
matches the type member function of the base class, the
base class member function is executed
• Similarly, the p->ppp() is executed after assigning the
address of the object “b” of the derived class “d2” to “p”,
again the member function of the base class is executed
• Accessing member functions of a class through the pointer
is example of early-binding or static binding. i.e. class type
matches the type of the pointer irrespective of the contents
of the pointer
Virtual and pure virtual
functions
• A virtual function is a special type of member function
• It is defined in the base class and may be redefined in any
class derived from this base class
• Its name in the base class and in the derived classes
remains the same
• Its definition in these classes may be different
• The virtual function in derived class is executed through
pointer of the public base class
• A virtual function is declared by writing the word “virtual”
before function declaration in the base class
• The use of the word “virtual” before function declaration
in derived classes is optional
• In virtual function execution, late binding or dynamic
binding occurs, because the compiler selects the function
to be called based on the contents of the pointer and not
on the basis of the type of the pointer
Virtual and pure virtual
functions (con’t)
• Once a function is declared virtual in a base class,
it becomes virtual in all derived classes, even the
keyword virtual is not written in its definition in
the derived classes
• The derived classes may have different versions
of a virtual function
• A redefined function in derived classes is said to
override the base class function
• In executing virtual function, the complier selects
the function to be called based on the contents of
the pointer (i.e. address) and not on the basis of
the type of the pointer (i.e. class)
• Without using keyword virtual, function to be
called based on the contents of the pointer (i.e.
class) and not on type of pointer (i.e. address)
An example of Virtual


1
2
functions
// vfunction1.cpp
// An example of a virtual function
• 3 #include <iostream.h>
• 4
• 5
• 6
• 7 class bb
• 8 {
• 9 public:
• 10 virtual void ppp()
• 11 {
• 12 cout<<“It is the base class”<<endl;
• 13 }
• 14 };
• 15 class d1 : public bb
• 16 {
• 17 public:
• 18 void ppp()
• 19 {
• 20 cout<<“It is the first derived class”<<endl;
• 21 }
• 22 };
• 23 class d2 : public bb
• 24 {public:
• 25 void ppp()
• 26 {
• 27 cout<<“It is the second derived class”<<endl;
• 28 }
• 30 int main()
• 31 {
• 32 bb *p;
• 33 d1 a;
• 34 d2 b;
• 35 p = &a;
• 36 p-> ppp();
• 37 p = &b;
• 38 p-> ppp();
• 39 return 0; // indicates successful termination
• 40 } // end main
It is the first derived class
It is the second derived class
Virtual functions (con’t)
• In the previous example, the keyword “virtual” appears
only in the definition of the base class “bb”.
• Each derived class “d1” and “d2” and base class “bb”
have a member function with the same name, i.e. ppp()
• The statement “p=&a” assigns address of object “bb”
to the pointer object “p”
• When p->ppp() is executed, the pointer object of the
base class contains the address of the object of the
derived class “d1” and the virtual member function of
the derived class “d1” is executed
• Similarly, when the p->ppp() is executed the pointer
object “p” of the base class contains the address of the
derived class “d2” and the virtual member function of
the derived class “d2” is executed
• In executing virtual function, the compiler selects the
function to be called based on the contents of the
pointer and not on the basis of the type of the pointer
Pure virtual function
• The virtual function that is only declared but
not defined in the base class is called the
pure virtual functions
• A function is made pure virtual by preceding
its declaration with the keyword “virtual” and
by postfixing it with = 0
• The class that contains the pure virtual
function exists only to act as a parent or base
of the derived class
• The base class that has one or more pure
virtual functions is called the Abstract base
class
• An object of abstract class cannot be defined.
Virtual function guidelines
• A member function of the base class to be
overridden should be declared with keyword
“virtual”
• In the presence of virtual member function
in the base class, the destructors of that
class should also be declared as virtual. The
reason is that the correct destructor will
remove or clean it up
• Calling an overriding function, supply of the
same member and type of parameters must
match the number and type in the
declaration of the function in the base class
Virtual function properties
and reasons
• It must be a member function of a
base class
• It must start with the keyword
“virtual”
• A call to a virtual function is resolved
during run-time, this mechanism is
also known as late binding
An example of pure virtual


1
2
functions
// pvfunction1.cpp
// An example of a pure virtual function
• 3 #include <iostream>
• 4
• 5
• 6
• 7 class bb
• 8 {
• 9 public:
• 10 virtual void ppp() = 0;
• 11 };
• 12 class d1 : public bb
• 16 {
• 17 public:
• 18 void ppp()
• 19 {
• 20 cout<<“First Derived class”<<endl;
• 21 }
• 22 };
• 23 class d2 : public bb
• 24 void ppp()
• 25 {
• 26 cout<<“Second Derived class”<<endl;
• 27 }
• 28 };
• 29 void main()
• 30 {
• 31 bb *p;
• 32 d1 a;
• 33 d2 b;
• 34 p = &a;
• 35 p-> ppp();
• 36 p = &b;
• 37 p-> ppp();
• 38 return 0; // indicates successful termination
• 39 } // end main
First Derived class
Second Derived class
Abstract Base classes and
Concrete derived classes
• The base class that has one or more pure
virtual functions is called the Abstract
Base class
• These classes (Abstract base classes)
designed as a framework for derived
classes
• An abstract base class cannot be
instantiated. i.e. an object of its type
cannot be defined. But a pointer to an
abstract base class can be defined
• The derived class that does not have any
pure virtual function is called Concrete
Derived class
• The derived classes usually have their own
Abstract Base classes and
Concrete derived classes
(con’t)
• In OOP a hierarchy of classes are defined
• The Abstract Base class is defined at the
top of this hierarchy
• The Concrete Derived classes are derived
from Abstract Base class
• The pure virtual functions are declared in
the base class
• Each derived class contains its own
version of these pure virtual functions
• In this way a uniformity is achieved within
the hierarchy of the class

You might also like