100% found this document useful (1 vote)
112 views

C Unit 3

The document discusses operator overloading in C++. It defines operator overloading as treating operators like +, -, etc. as polymorphic functions that can have different behaviors depending on the type of arguments. It lists the operators that can and cannot be overloaded. It also provides rules for operator overloading and discusses overloading unary operators like ++ and --, binary operators using member functions and friend functions, and relational operators.

Uploaded by

rogitha
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
100% found this document useful (1 vote)
112 views

C Unit 3

The document discusses operator overloading in C++. It defines operator overloading as treating operators like +, -, etc. as polymorphic functions that can have different behaviors depending on the type of arguments. It lists the operators that can and cannot be overloaded. It also provides rules for operator overloading and discusses overloading unary operators like ++ and --, binary operators using member functions and friend functions, and relational operators.

Uploaded by

rogitha
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/ 27

23UBCAC23: OBJECT ORIENTED PROGRAMMING CONCEPTS USING C++

Unit – 3:- Overloading unary, binary operators – Overloading Friend functions –type conversion –
Inheritance: Types of Inheritance – Single, Multilevel, Multiple, Hierarchal,Hybrid, Multi path
inheritance – Virtual base Classes – Abstract Classes.
4.1 Operator Overloading:-

Introduction:- Operator Overloading is a specific case of Polymorphism ( part of the OO nature


of the language ) in which some or all operator like +, -, =, == etc., are treated as polymorphic
functions and as such have different behaviors depending on the type of its arguments
(performing many actions witha single operator).

Consider the following operation,

add ( a, multiply( b,c) ) – function notation

Using Operator Overloading permits a more concise(short) way of writing it a + b*c

Operators that are overloaded are listed below,

Aritmetic Operator +,-,*,/,%

Relational Operator < , <= , > , >= , != , ==

Logical Operator && , !! , !

Assignment Operator =

Unary Operator ++ , -- , -

Input and Output Operator >> , <<

Operator that are not overloaded are listed below,

 Size of Operator( sizeof )


 Membership Operator( . )
 Pointer to Member Operator( .* )
 Scope Resolution Operator( :: ) and
 Conditional Operators( ?: ) etc

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 1


Rules for Operator Overloading:-

1. Only existing operators can be overloaded. New operators cannot be overloaded.

2. The overloaded operator must have at least one operand that is of user defined type.

3. We cannot change the basic meaning of an operator. That is to say, We cannot redefine the plus(+)
operator to subtract one value from the other.

4. Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.

5. There are some operators that cannot be overloaded like

 Size of Operator( sizeof )


 Membership Operator( . )
 Pointer to Member Operator( .* )
 Scope Resolution Operator( :: ) and
 Conditional Operators( ?: ) etc

6. Binary operators overloaded through a member function take one explicit argument and those which
are overloaded through a friend function take two explicit arguments.

7. When using binary operators overloaded through a member function, the left hand operand must be
an object of the relevant class.

8. Binary arithmetic operators such as +,-,* and / must explicitly return a value. They must not attempt
to change their own arguments.

9. We cannot use “friend” functions to overload certain operators.However, member function can be
used to overload them.

10. Unary operators, overloaded by means of a member function, take no explicit arguments and return
no explicit values,

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 2


Defining Operator Function:-

To define an additional task to an operator, we must specify the relation to the class to which the
operator is applied. This is done with the help of special function called operator function.

The general form of an operator function is,

return-type class-name :: operator op (arglist)

//function body (task defined)

Here, return-type - type of returned by the specified operation

op - operator being overloaded(preceded by keyword operator and op is function name)


and

arglist- argument list

Operator functions must be either member function (non- static) or friend function. A basic difference
between that a

 Friend Function will have only one argument for unary operators and two arguments for binary
operator.
 Member Function have no arguments for unary operator and one argument for binary operator.

Operator functions are declared in the class using prototype as follows,

a) void operator ++ ( );
b) void operator -- ( );
c) void operator – ( );
d) num operator + ( num ); // binary operator using member function
e) friend num operator * ( int,num ); // binary operator using friend function
f) void operator = ( num ); // Assignment operator

The process of overloading involves the following steps:

1. Create a class that defines the data type that is to be used in the overloading operation.
2. Declare the operator function
i.e operator op( ) in the public part of the class( either member function or friend function).

3. Define the operator function to implement the require operations.

Overloaded operator functions can be invoked by expression

op X (or) X op Ex: ++ X; (or) X ++ ;

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 3


Overloading Unary Operator:-

 Overloading without explicit argument to an operator function is called as unary operator


overloading
 The operator ++ ( increment ), -- (decrement), - (minus) are unary operators.
 The unary operator ++, --, - can be used prefix or suffix with the functions.
i.e ++ X or X ++
 These operators have only single operand( called as unary operator)

Syntax:

return-type class-name :: operator operator-symbol ( )


{
// body of function
}

Example:-

#include<iostream.h> void num :: operator ++()


#include<conio.h> {
a=++a;
class num b=++b;
{ c=++c;
private: d=++d;
int a,b,c,d; }
public:
num(int p,int q,int r,int s) void main()
{ {
a=p; clrscr();
b=q; num n1(10,20,30,40);
c=r; cout<<"Before Increment..."<<endl;
d=s; n1.display();
} ++n1;
cout<<"After Increment..."<<endl;
void display() n1.display();
{ getch();
cout<<"A="<<a; }
cout<<" B="<<b;
cout<<" C="<<c; Output:-
cout<<" D="<<d; Before Increment...
} A=10 B=20 C=30 D=40
After Increment…
void operator ++(); A=11 B=21 C=31 D=41
};

Explanation:- The operator ++( ) overloads the unary operators ++. When the operator is used with
integer (or) float variables, it‟s value is increased by “1”. In this function, ++ operator preceded each
member variable in class.

In main( ), the statement ++n1 calls the function operator ++ ( ), where n1 is an object of the class num.

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 4


Overloading Binary Operator:-

 Overloading with a single parameter is called as binary operator overloading.


 Like unary operator, binary operators can also be overloaded.
 Binary operator requires two operands.
 It can also be overloaded using member function and friend function.

1. Overloading Binary Operator using member function:-

 In member function they require one argument to overload.


 The argument contains the value of the object which is right side of the operator.
 If we want to perform the addition of two object o1 and o2 then,
operator (num o2)

Here, num is class-name, o2 is an object

To call function operator, the statement as,

o3 = o1 operator-name o2 ;

Here, the data member o1 passed directly and o2 passed as argument.

2. Overloading Binary Operator using friend function:

 The friend function requires two operands to be passed as arguments.


o3 = o1 + o2;
o3 = operator + (o1,o2);

Both the statements have the same meaning. In the second statement, two objects are passed to the
operator function.

Syntax:

return-type operator operator-symbol (argument list)

// body of function

Write After diagram:

As a rule, in overloading of binary operators, the left-hand operand is used to invoke the operator
function and the right-hand operand is passed as an argument.

We can avoid the creation of the temp object by replacing the entire function body by the following
statement: return complex ( ( a + k.a ),( b + k.b ) );

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 5


DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 6
Overloading Relational Operator:-

 There are various relational operators supported by c++ language, which can be used to compare c++
built-in data types.
For example,
a) Less than ( < )
b) Less than or equal to ( < = )
c) Greater than ( > )
d) Greater than or equal to ( > = )
e) Equal to ( == )
f) Not equal to ( != )

 We can overload any of these operators, which can be used to compare the object of the class.
Following example explains how a „ < ’ operator can be overloaded and similar way you can
overload other relational operator.

Syntax:-
return-type class-name :: operator operator-name (arglist)
{
// body of function
}
Example:-
#include<iostream.h>
#include<conio.h>

class num
{
private:
int a;
public:
num(int x)
{
a = x;
}

int operator < (num k)


{
return ( a < k.a);
}
};

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 7


void main()
{
clrscr();
num n1(10),n2(20);
if(n1<n2)
{
cout<<"n1 is less than n2";
}
else
{
cout<<"n1 is greater than n1";
}
getch();
}

Output:-
n1 is less than n2

Explanation:- In the above program, from main( ) relational operator function (<) is invoked and
returnthe value. i.e ,n1 object value is 10 and n2 object value is 20. It checks condition and return
corresponding value ( either true = 1 or false = 0 ). Finally it return 1 from operator function to
main() and display true conditi on i.e “n1 is less than n2”.

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 8


4.2 Operator Overloading using Friend Function in C++ with Examples:
We need to remember the following pointers while working with Operator Overloading in C++
Using Friend Function.
1. The Friend function in C++ using operator overloading offers better flexibility to the
class.
2. The Friend functions are not a member of the class and hence they do not have „this‟
pointer.
3. When we overload a unary operator, we need to pass one argument.
4. When we overload a binary operator, we need to pass two arguments.
5. The friend function in C++ can access the private data members of a class directly.
6. An overloaded operator friend could be declared in either the private or public section of a
class.
7. When redefining the meaning of an operator by operator overloading the friend function,
we cannot change its basic meaning. For example, we cannot redefine minus operator + to
multiply two operands of a user-defined data type.
Syntax to use Friend Function in C++ to Overload Operators:

Using Friend Function to Overload Unary Operator in C++:


We can also overload a unary operator in C++ by using a friend function. The overloaded ++
operator relative to the Test class using a member function is shown in the below example.
#include <iostream>
using namespace std;
class Test
{
int a, b, c;
public:
Test()
{
a = b = c = 0;
}
Test(int i, int j, int k)
{
a = i;

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 9


b = j;
c = k;
}
// use a reference to overload the ++
friend Test operator ++ (Test & op1);
friend Test operator ++ (Test & op1, int not_used);
void Display();
};
/* Overload prefix ++ using a friend function.
This requires the use of a reference parameter. */
Test operator ++(Test & op1)
{
op1.a ++;
op1.b ++;
op1.c ++;
return op1;
}
/* Overload postfix ++ using a friend function.
This requires the use of a reference parameter. */
Test operator ++ (Test & op1, int not_used)
{
Test temp = op1;
op1.a ++;
op1.b ++;
op1.c ++;
return temp;
}
// Display a, b, c coordinates.
void Test::Display()
{
cout << a << ", ";
cout << b << ", ";
cout << c << "\n";
}
int main()
{
Test a (12, 22, 33);
a.Display();
++a; // prefix increment

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 10


a.Display();
a++; // postfix increment
a.Display();
return 0;
}
Output:

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 11


4.3 Type Conversion in C++

Type conversion can be done in two ways in C++, one is implicit type conversion, and the second is explicit
type conversion.
Those conversions are done by the compiler itself, called the implicit type or automatic type conversion. The
conversion, which is done by the user or requires user interferences called the explicit or user define type
conversion. Let's discuss the implicit and explicit type conversion in C++.

1) Implicit Type Conversion


The implicit type conversion is the type of conversion done automatically by the compiler without any human
effort. It means an implicit conversion automatically converts one data type into another type based on some
predefined rules of the C++ compiler. Hence, it is also known as the automatic type conversion.
For example:
1. int x = 20;
2. short int y = 5;
3. int z = x + y;

In the above example, there are two different data type variables, x, and y, where x is an int type, and the y is of
short int data type. And the resultant variable z is also an integer type that stores x and y variables. But the C++
compiler automatically converts the lower rank data type (short int) value into higher type (int) before resulting
the sum of two numbers. Thus, it avoids the data loss, overflow, or sign loss in implicit type conversion of C++.
Order of the typecast in implicit conversion.

The following is the correct order of data types from lower rank to higher rank:
1. bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int -> long long int -
> float -> double -> long double

Program to convert int to float type using implicit type conversion

Let's create a program to convert smaller rank data types into higher types using implicit type conversion.
Program1.cpp
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // assign the integer value
6. int num1 = 25;
7. // declare a float variable
8. float num2;
9. // convert int value into float variable using implicit conversion
10. num2 = num1;
11. cout << " The value of num1 is: " << num1 << endl;
12. cout << " The value of num2 is: " << num2 << endl;
13. return 0;
14. }

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 12


Output
The value of num1 is: 25
The value of num2 is: 25
Program to convert double to int data type using implicit type conversion

Let's create a program to convert the higher data type into lower type using implicit type conversion.
Program2.cpp
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int num; // declare int type variable
6. double num2 = 15.25; // declare and assign the double variable
7.
8. // use implicit type conversion to assign a double value to int variable
9. num = num2;
10. cout << " The value of the int variable is: " << num << endl;
11. cout << " The value of the double variable is: " << num2 << endl;
12. return 0;
13. }
Output
The value of the int variable is: 15
The value of the double variable is: 15.25

2) Explicit type conversion

Conversions that require user intervention to change the data type of one variable to another, is called
the explicit type conversion.
In other words, an explicit conversion allows the programmer to manually changes or typecasts the data type
from one variable to another type. Hence, it is also known as typecasting.
Generally, we force the explicit type conversion to convert data from one type to another because it does not
follow the implicit conversion rule.
The explicit type conversion is divided into two ways:
1. Explicit conversion using the cast operator
2. Explicit conversion using the assignment operator
Program to convert float value into int type using the cast operator
Cast operator: In C++ language, a cast operator is a unary operator who forcefully converts one type into
another type.
Let's consider an example to convert the float data type into int type using the cast operator of the explicit
conversion in C++ language.
Program3.cpp
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. float f2 = 6.7;
6. // use cast operator to convert data from one type to another
7. int x = static_cast <int> (f2);
8. cout << " The value of x is: " << x;
9. return 0;
DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 13
10. }
Output
The value of x is: 6

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 14


4.4 INHERITANCE:-

Introduction:-

One of the most important concepts in Object Oriented Programming is that of


Inheritance. Inheritance allows us to define one class items to another class, which makes easier to
create and maintain on application. This also provides an opportunity to reuse the code functionality
and fast implementation time.

When creating a class, instead of writing completely new data members and member
function, the programmer can designate that the new class should inherit the members of an existing
class. This existing class is called the “Base Class” and the new class is referred as the “Derived Class”.

Definition of Inheritance:-

Inheritance in Object Oriented Programming can be described as process of creating a


new class from existing classes. New Classes inherit some of the properties (member variables) and
behavior (member functions) of the existing classes. An existing class that is “parent” of a new class is
called a “child”

Note: Base class / Super class / Parent class are same

Derived class / sub class / child class are same

The General Form of a defining derived class is

Class Derive-class-name : Visibility-mode Base-class-name

--------- // member of derived class

};

Benefits of Inheritance:-

 One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses.
 Inheritance can also make application code more flexible to change because classes that
inherit from a common superclass can be used interchangeably.
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.
 Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class
 Overriding -With inheritance, we will be able to override the methods of the base class so
that meaningful implementation of the base class method can be designed in the derived class.

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 15


Disadvantage of Inheritance:-

1. Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly
coupled. This means one cannot be used independent of each other.

2. Also with time, during maintenance adding new features both base as well as derived classes are
required to be changed. If a method signature is changed then we will be affected in both cases
(inheritance & composition).
3. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of
using that method.
4. It increased time/effort it takes the program to jump through all the levels of overloaded classes.

Types of Inheritance:-

A class can inherit properties (data) and behaviours (functions) in various levels used for
derivation. In c++, there are six types of inheritance, that are listed below,

1. Single Inheritance Example:- Single Inheritance

2. Multiple Inheritance #include<iostream.h>


#include<conio.h>
3. Hierarchical Inheritance
class A
4. Multi-level Inheritance {
protected:
5. Hybrid Inheritance and int id;
};
6. Multi-Path Inheritance
class B : public A
1. Single Inheritance:- {
private:
When only one base class is used for derivation of a char name[20];
public:
class is not used as base class, such type of inheritance void getdata()
{
between one base and derived class is known as inheritance. cout<<"\nEnter ID and Name: ";
cin>>id>>name;
}
A
void display()
{

B cout<<"ID:"<<id<<endl<<"Name:"<<name;
}
};
fig. Single Inheritance
void main()
Here, A is base class, B is derived class. {
Further no class derived from B. clrscr();
B b; Output:-
b.getdata();
b.display(); Enter ID and Name: 10 Rahul
getch(); ID: 10
} Name: Rahul

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 16


Syntax:- Example:- Multiple Inheritance
class base-class-name #include<iostream.h>
#include<conio.h>
{
---------//base class members class A
}; {
class derived-class-name : visibility-mode base-class-name protected:
{
int id;
--------- //derived class members
};
};
class B
{
2. Multiple Inheritance:-
protected:
When two or more base class are used for char name[20];
};
derivation of a class, it is called multiple inheritance.
class C : public A,B
{
private:
A B float height;
public:
void getdata()
{
C cout<<"Enter ID,name and height:";
cin>>id>>name>>height;
}
void display()
fig. Multiple Inheritance {
class C inherits properties of both A and B base class, cout<<"ID:"<<id<<endl<<"Name:"<<name<<endl<
<"Height:"<<height;
further C is not used for base class. }
};
Syntax:-

class base-class-name1 void main()


{
{
clrscr(); Output:-
------ //base class members
C c;
}; Enter ID, Name and Height:
class base-class-name2 c.getdata();
c.display(); 10 Rahul 5.11
{
getch(); ID: 10
----- //base class members
} Name: Rahul
};
Height: 5.11

class derived-class-name : visibility-mode base-class-name1, base-class-name2

{
----- //derived class members
};

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 17


3. Hierarchical Inheritance:- Example:- Hierarchical Inheritance

When a single base class is used to derivation of #include<iostream.h>


#include<conio.h>
two or more classes, it is known as
class A
hierarchical inheritance {
protected:
int id;
};
A
class B : public A
{
protected:
B C
char name[20];
};

fig. Hierarchical Inheritance class C : public A


{
Here, A is base class and B, C are derived class. private:
float height;
Further B and C are not used for deriving class. public:
void getdata()
Syntax:- {
cout<<"Enter ID and Height:";
class base-class-name1 cin>>id>>height;
{ }
----- // base class members void display()
}; {

class derived-class-name1 : visibility-mode cout<<"ID:"<<id<<endl<<"Height:"<<height;


base-class-name }
{ };
------//derived class-name1 members
}; void main()
{ Output:-
class derived-class-name2 : visibility-mode clrscr();
base-class-name C c; Enter ID and Height: 10 5.11
{ c.getdata(); ID: 10
------//derived class-name2 members c.display(); Height: 5.11
}; getch();

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 18


4. Multi-Level Inheritance:- Example:- Multilevel inheritance

#include<iostream.h>
#include<conio.h>
When a class is derived from another derived class
class A
i.e. derived class act as base class. Such types of inheritance {
protected:
is known as multi-level inheritance. int id;
};

A class B : public A
{
protected:
B char name[20];
};

class C : public B
C
{
private:
float height;
Fig. Multi-level inheritance public:
void getdata()
Here, B is derived class from class A(base class). {
cout<<"Enter id,name and height:";
Again B acts as base class to class C, which is derived class. cin>>id>>name>>height;
}
Finally, there is no more derivation from class C.
void display()
{
Syntax:-
cout<<"ID:"<<id<<endl;
class base-class-name1 cout<<"Name:"<<name<<endl;
{ cout<<"Height:"<<height;
----- //class-name1 members }
}; };
class intermediate-base-class-name2 : visibility-mode
base-class-name1 void main()
{ {
----- //class-name2 members clrscr();
}; C c;
class derived-class-name3 : visibility-mode c.getdata();
intermediate-base-class-name2 c.display();
{ getch();
----- //clas-name3 members }
};
Output:-

Enter id, name and height: 10 Rahul 5.11


ID: 10
Name: Rahul
Height: 5.11

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 19


5. Hybrid Inheritance:- Example:- Hybrid Inheritance

Combining more than one type of inheritance is known #include<iostream.h>


#include<conio.h>
as Hybrid Inheritance.
class A
i.e. here, combining Multi-Level and Single Inheritance {
protected:
int id;
A };

class B : public A
B D {
protected:
char name[20];
};
C
class C
{
Fig. Hybrid Inheritance protected:
float height;
Here, class B acts as derived class for class A and base class };

for class C. C is derived class form class B and class D. class D : public B,C
{
private:
float weight;
Syntax: public:
void getdata()
class base-class-name1 {
{ cout<<"Enter id,name,height and
----- //class-name1 members weight:";
}; cin>>id>>name>>height>>weight;
}
class intermediate-base-class-name2 : visibility-mode void display()
base-class-name1 {
{ cout<<"ID:"<<id<<endl;
----- //class-name2 members cout<<"Name:"<<name<<endl;
}; cout<<"Height:"<<height<<endl;
class base-class-name3 cout<<"Weight:"<<weight<<endl;
{ }
----- //class-name3 members };
};
class derived-class-name4 : visibility-mode void main() Output:
{
intermediate-base-class-name2,base-class-name3 clrscr()
Enter id,name,height and weight:
D d; 10 Rahul 5.11 78.5
{
d.getdata(); ID: 10
----- //derived-class-name4 members
d.display(); Name: Rahul
};
getch(); Height: 5.11
} Weight: 78.5

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 20


6. Multi-Path Inheritance:- Example:- Multipath Inheritance

When a class is derived from two (or) more classes that are #include<iostream.h>
derived from same base class, such type of inheritance #include<conio.h>
is known as Multi-Path Inheritance.
class A
{
A protected:
int id;
};
B C class B : virtual public A
{
protected:
D char name[20];
};

class C : virtual public A


Fig. Multi-Path Inheritance {
protected:
Here, class B and C acts as derived class for base class A float height;
and base class for class D. };
i.e class D is derived from class B and C.
class D : public B,C
While executing the program, ambiguity is generated. {
Hence, virtual keyword is used to avoid ambiguity. private:
float weight;
public:
Syntax:- void getdata()
{
class base-class-name1 cout<<"Enter id,name,height and
{ weight:";
----- // base class members cin>>id>>name>>height>>weight;
}; }
class derived-class-name1 : visibility-mode void display()
base-class-name1 {
{ cout<<"ID:"<<id<<endl;
------//derived class-name1 members cout<<"Name:"<<name<<endl;
}; cout<<"Height:"<<height<<endl;
class derived-class-name2 : visibility-mode cout<<"Weight:"<<weight<<endl;
}
{ };
------//derived class-nam2 members
}; void main() Output:
class derived-class-name3 : visibility-mode {
derived-class-name1,derived-class-name2 clrscr(); Enter id,name,height and weight:
{ D d; 10 Rahul 5.11 78.5
----- //derived class-name3 member d.getdata(); ID: 10
}; d.display(); Name: Rahul
getch(); Height: 5.11
} Weight: 78.5
DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 21
base-class-name1

DEPARTMENT OF COMPUTER APPLICATION-RASC-N.MANIMOZHI-AP Page 22


4.4 Virtual Base Classes
We have just discussed a situation which would require the use of both multiple and multi level
inheritance. Consider a situation, where all the three kinds of inheritance, namely multi-level,
multiple and hierarchical are involved.

Let us say the 'child' has two direct base classes „parent1‟ and „parent2‟ which themselves has a
common base class „grandparent‟. The child inherits the traits of „grandparent‟ via two separate
paths. It can also be inherit directly as shown by the broken line. The grandparent is sometimes
referred to as „INDIRECT BASE CLASS‟. Now, the inheritance by the child might cause some
problems. All the public and protected members of „grandparent‟ are inherited into „child‟ twice, first
via „parent1‟ and again via „parent2‟. So, there occurs a duplicacy which should be avoided.

The duplication of the inherited members can be avoided by making common base class as the
virtual base class: for e.g.
class g_parent
{
//Body
};
class parent1: virtual public g_parent
{
// Body
};

class parent2: public virtual g_parent


{
// Body
};
class child : public parent1, public parent2
{
// body
};

When a class is virtual base class, C++ takes necessary care to see that only one copy
of that class is inherited, regardless of how many inheritance paths exists between
virtual base class and derived class. Note that keywords „virtual‟ and „public‟ can be
used in either order.

//Program to show the virtual base class


#include<iostream.h>
#include<conio . h>
class student // Base class declaration
{
protected:
int r_no;
public:
void get_n (int a)
{ r_no = a; }
void put_n (void)
{ cout << “Roll No. “ << r_no<< “ln”;}
};
class test : virtual public student // Virtually declared common
{ //base class 1
protected:
int part1;
int part2;
public:
void get_m (int x, int y)
{ part1= x; part2=y;}
void putm (void)
{
cout << “marks obtained: “ << “\n”;
cout << “part1 = “ << part1 << “\n”;
cout << “part2 = “<< part2 << “\n”;
}
};
class sports : public virtual student // virtually declared common
{ //base class 2
protected:
int score;
public:
void get_s (int a) {
score = a ;
}
void put_s (void)
{ cout << “sports wt.: “ <<score<< “\n”;}
};
class result: public test, public sports //derived class
{
private : int total ;
public:
void show (void) ;
};
void result : : show (void)
{ total = part1 + part2 + score ;
put_n ( );
put_m ( );
put_s ( ) ; cout << “\n total score= “ <<total<< “\n” ;
}
main ( )
{
clrscr ( ) ;
result S1 ;
S1.get_n (345)
S1.get_m (30, 35) ;
S1.get-S (7) ;
S1. show ( ) ;
}

//Program to show hybrid inheritance using virtual base classes


#include<iostream.h>
#include<conio.h>
Class A
{
protected:
int x;
public:
void get (int) ;
void show (void) ;
};
void A : : get (int a)
{ x = a ; }
void A : : show (void)
{ cout << X ;}
Class A1 : Virtual Public A
{

protected:
int y ;
public:
void get (int) ;
void show (void);
};
void A1 :: get (int a)
{ y = a;}
void A1 :: show (void)
{
cout <<y ;
{
class A2 : Virtual public A
{
protected:
int z ;
public:
void get (int a)
{ z =a;}
void show (void)
{ cout << z;}
};
class A12 : public A1, public A2
{
int r, t ;
public:
void get (int a)
{ r = a;}
void show (void)
{t =x+y+z +r;
cout << “result =” << t ;
}
};
main ( )
{
clrscr ( ) ;
A12 r ;
r.A : : get (3)
; r.A1 : : get
(4) ; r.A2 : :
get (5) ; r.get
(6) ;
r . show ( ) ;
}
4.5 Abstract Class
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are
used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide
definition to the pure virtual function, otherwise they will also become abstract class.

Characteristics of Abstract Class


1. Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be
created.
2. Abstract class can have normal functions and variables along with a pure virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will
become Abstract too.

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 f() = 0;

Example of Abstract Class

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();
}
Output : Implementation of Virtual Function in Derived class

In the above example Base class is abstract, with pure virtual show() function, hence we cannot
create object of base class.

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