0% found this document useful (0 votes)
34 views

Unit 3 Notes

Operator overloading in C++ allows operators to be redefined for user-defined types like classes. This allows operators to work with objects of user-defined classes in the same way they work with built-in types. The summary discusses overloading unary operators like increment ++ and decrement -- for a complex number class. It also discusses overloading binary operators like addition + and subtraction - for complex number classes by defining operator functions as member or friend functions. The last sentence provides an example of overloading the + operator to concatenate two strings by defining the operator+ function for a string class.

Uploaded by

Pratibha Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Unit 3 Notes

Operator overloading in C++ allows operators to be redefined for user-defined types like classes. This allows operators to work with objects of user-defined classes in the same way they work with built-in types. The summary discusses overloading unary operators like increment ++ and decrement -- for a complex number class. It also discusses overloading binary operators like addition + and subtraction - for complex number classes by defining operator functions as member or friend functions. The last sentence provides an example of overloading the + operator to concatenate two strings by defining the operator+ function for a string class.

Uploaded by

Pratibha Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Computer Programming

[3 Semester]
rd

By,
Vinni Sharma
Associate Professor
BIT Durg

1
Unit III
Operator Overloading
and
Inheritance
Operator Overloading
C++ has the ability to provide the operators with a special meaning for a
data type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that
we can concatenate two strings by just using +.
Some examples where arithmetic operators may be overloaded are
Complex Numbers, Fractional Numbers, Big Integers, etc.
 Unary operators, overloaded by means of a member function, take
no explicit argument and return no explicit values.
 Binary operators overloaded through a member function take one
explicit argument
Operator Overloading contd.
We can overload all the C++ operators except the following:
• Class members access operator (. and .*)
• Scope resolution operator (: :)
• Size operator(sizeof)
• Condition operator (? :)

Syntax:
return-type class-name :: operator op( arg-list) { function body }
Write a C++ program to show Overloading of Unary
operators increment “++” and decrement “--”
void operator --()
#include<iostream.h> {
#include<conio.h> a=--a;
class complex b=--b;
{ }
int a,b; void display()
public: {
complex(){} cout<<a<<"+\t"<<b<<"i"<<endl;
void getvalue() }
{ };
cout<<"Enter the real and imag void main()
part:"; {
cin>>a>>b; clrscr();
} complex obj;
void operator ++ () obj.getvalue();
{ obj++;
a=++a; cout<<"Increment Complex Number\n";
b=++b; obj.display();
} obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}
Write a C++ program to explain Overloading of
Binary operator “+” to add two complex nos.
#include<iostream.h>
# include<conio.h>
class complex {
int main()
private:
{
int real, imag;
cout<<“Enter the real and imag part of 1st complex no.: ”;
public:
cin>>a>>b;
complex(int r = 0, int i =0) {real = r; imag = i;}
cout<<“Enter the real and imag part of 2nd complex no.: ”;
// This is automatically called when '+' is used with
cin>>c>>d;
// between two Complex objects
complex c1(a,b), c2(c,d);
complex operator + (complex obj)
complex c3 = c1 + c2; // An example call to "operator+“
{
cout<<“The two complex nos and their sum are: ”
complex res;
c1.print();
res.real = real + obj.real;
c2.print();
res.imag = imag + obj.imag;
c3.print();
return res;
}
}
void print()
{
cout <<“\n”<< real << " + i" << imag << endl; }
};
Operator Overloading Contd.
The process of overloading involves the following steps:-
• Create a class that defines the data type that is used in the overloading operation.
• Declare the operator function operator op() in the public part of the class
• It may be either a member function or friend function.
• Define the operator function to implement the required operations

Overloaded operator functions can be invoked by expressions such as


op x or x op; for unary operators and
x op y for binary operators.
operator op(x); for unary operator using friend function
operator op(x,y); for binary operator using friend function.
Write a C++ program to show Overloading of
Unary operator “-” using friend function
void operator - (sample obj)
#include<iostream.h> {
#include<conio.h> obj.a=-obj.a;
class sample obj.b=-obj.b;
{ obj.c=-obj.c;
int a,b,c; }
public: void main()
sample(int x,int y,int z) {
{ sample s1(2,5,-7);
a=x; cout<<“\nOriginal Data Entered: ”;
b=y; s1.display();
c=z; operator –(s1);
} cout<<“\nData after using operator: ”;
void friend operator - (sample obj); s1.display();
void display() getch();
{ }
cout<<“\nClass Data:”;
cout<<a<<“\t”<<b<<“\t”<<c;
}
};
Write a C++ program to explain Overloading of Binary operator
“-” to substract two complex nos using friend function.
complex operator -(complex p, complex q)
{
class complex
complex w;
{
w.real=p.real-q.real;
float real,imag;
w.imag=p.imag-q.imag;
public:
return w;
complex(float r=0,float i=0)
}
{
real=r;
void main()
imag=i;
{
}
float a,b,c,d;
void show()
cout<<“Enter the 1st Complex no: ”;
{
cin>>a>>b;
cout<<“\n”<<real<<”+i”<<imag;
cout<<“Enter the 2nd Complex no: ”;
}
cin>>c>>d;
friend complex operator -(complex , complex );
complex c1(a,b),c2(c,d);
};
complex c3;
c3=operator -(c1,c2);
cout<<“The two complex nos and their difference is: ”;
c1.show();
c2.show();
c3.show();
}
Operator Overloading Contd.
• Unary operators, overloaded by means of a member function, take no
explicit argument and return no explicit values. But, those overloaded
by means of a friend function take one reference argument (the
object of the relevant class).
• Binary operators overloaded through a member function take one
explicit argument and those which are overloaded through a friend
function take two explicit arguments.

Note: Overloading an operator should not change its basic meaning. For example assume the +
operator can be overloaded to subtract two objects. But the code becomes unreachable.
Manipulation of Strings using
Operator Overloading
• There are no direct operator that could act upon the strings or
manipulate the strings.
• Although there are these limitations exist in C++, it permits us to
create our own definitions of operators that can be used to
manipulate the strings very much similar to the decimal number.
• We can manipulate strings by operator overloading.
• String Manipulation in C++ uses many string functions which we can
use to manipulate the strings, therefore we have to include string
library (#include <string.h>). 
Write a C++ program to explain Overloading of Binary
operator “+” to concatenate two strings.
#include<iostream.h>
#include<string.h>
void main()
# include <conio.h>
{
class string
clrscr();
{
string s1, s2, s3;
private:
s1.input();
char str[25];
s2.input();
public:
cout<<"\n First String ";
void input()
s1.display(); //Displaying First String
{
cout<<"\n Second String ";
cout<<"\n Enter String : ";
s2.display(); //Displaying Second String
cin>>str;
s3=s1+s2; //Strings are concatenated directly using '+' operator
}
cout<<"\n Concatenated String : ";
void display()
s3.display();
{
getch();
cout<<“The String is:” <<str;
}
}
string operator +(string x) //Concatenating String function defined
{
string s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
};
Write a C++ program to explain Overloading of Binary
operator “==” to compare two strings.
#include<iostream.h>
#include<string.h>
# include <conio.h> void main()
class string {
{ clrscr();
private: string s1, s2;
char str[25]; s1.input();
public: s2.input();
void input() cout<<"\n First String ";
{ s1.display(); //Displaying First String
cout<<"\n Enter String : "; cout<<"\n Second String ";
cin>>str; s2.display(); //Displaying Second String
} if (s1==s2) //Strings compared directly using ‘==' operator
void display() cout<<"\n Strings are equal ";
{ else
cout<<“The String is: <<”str; cout<<“\n Strings are not equal”;
} getch();
int operator==(string x) //Comparing String function defined }
{
int a=strcmp(str,x.str);
if (a==0)
return 1;
else
return 0;
}
};
RULES FOR OVERLOADING
OPERATORs :-
1) Only the operators already predefined in the C++ compiler can be overloaded.

2) Overloading cannot change operator's templates. for eg: the increment operator ++ is used only as
unary operator, it cannot be used as binary operator.

3) Overloading an operator should not change its basic meaning. for eg: the ++ operator cannot be
overloaded to subtract two objects.

4) Unary operator, overloaded by means of a member of a member function, takes no explicit


argument and return no explicit values. But those overloaded by means of a friend function global
function] takes one reference argument (the object of the relevant class).

5) Binary operators overloaded through a member function take one explicit argument and those
overloaded through a friend function [global function] take two explicit arguments.

6) The precedence and associativity of the operators remains same.


RULES FOR OVERLOADING
OPERATORs :-
7) There are some operators which cannot be overloaded :
1. :: Scope resolution operator.
2. . Class membership operator.
3. ?: ternary or conditional operator.
4. .* pointer to member operator.
5. ->* pointer to member operator.
6. Sizeof Size operator.

8) All overloaded operators except assignment (operator=) are inherited by derived classes.
9) If an operator can be used as either a unary or a binary operator (&, *, +, and -), you can
overload each of them separately.
10) Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must
be defined as member functions when overloaded, not friend functions.
11)  Binary arithmetic operators such as +,-,* and / must explicitly return a value. 
Function overloading
C++ allows you to specify more than one definition for a function name in the
same scope, which is called function overloading.
An overloaded declaration is a declaration that is declared with the same name as
a previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
When you call an overloaded function, the compiler determines the most
appropriate definition to use, by comparing the argument types you have used to
call the function with the parameter types specified in the definitions.
This process of selecting the most appropriate overloaded function is called
overload resolution.
You cannot overload function declarations that differ only by return type.
Write a C++ program to explain the concept of Overloading of
functions.
#include <iostream.h>
# include <conio.h> void main()
class printData { {
public: printData pd;
void print(int i) { pd.print(5); // Call print to print integer
cout << "Printing int: " << i << endl; pd.print(500.263); // Call print to print float
} pd.print("C"); // Call print to print character
void print(double f) { pd.add(12,45);
cout << "Printing Decimal: " << f << endl; pd.add(2,7,9);
} pd.add(2.45,6.74);
void print(char c) { getch();
cout << "Printing character: " << c << endl; }
}
void add(int a,int b) {
cout<<“Addition of two integers:”<<a+b;
}
void add(int a,int b,int c) {
cout<<“Addition of three integers:”<<a+b+c;
}
void add(double a,double b){
cout<<“Addition of two decimals:”<<a+b;
}
};
Inheritance in C++
Inheritance in C++ (contd.)
Inheritance in C++ (contd.)
• Re-usability is yet another feature of OOP's & C++ strongly supports the
concept of reusability.
• Once a class has been written and tested, it can be adopted by another
programmers …that is.. the C++ classes can be used again in several ways.
• This is basically created by defining the new classes, reusing the properties
of existing ones & this mechanism of deriving a new class from an old one is
called 'INHERITANCE'.
• The old class is called 'BASE' class and the new one is called 'DERIVED‘ class.
• The term reusability means reuse of properties of base class in the derived
class.
Inheritance in C++ (Example)
• Consider the vehicle hierarchy:
VEHICLE

AUTOMOBILE BICYCLE
LANDBASED

• Note that each entity is also a class


• Classes are used in an object centered paradigm as a
means of encapsulating common data and functions
shared by members of the class
Classes and Objects
Hierarchy
Classes Objects
VEHICLE myVehicle

LANDBASED myLandBased

AUTOMOBILE BICYCLE myBicycle myAuto


Multiple Parents & Common Ancestor

Vehicle
Example:

The derived class AutoBoat…Inherits


Attributes and Properties from LandBased WaterBased
Automobile, MotorBoat & Vehicle

Automobile MotorBoat

AutoBoat
Advantages of inheritance
When a class inherits from another class, there
are three benefits:
(1) We can reuse the methods and data of the existing class
(2) We can extend the existing class by adding new data and new
methods
(3) We can modify the existing class by overloading its methods
with your own implementations
Defining a Class Hierarchy
• Syntax:
class DerivedClassName : access-level BaseClassName
where
• access-level specifies the type of derivation
• private by default, or
• public
• Any class can serve as a base class
• Thus a derived class can also be a base class for some new
class defined….

25
Types of Inheritances in C++
Single Level Inheritance
Single Inheritance
The class stdmarks or instance object s1 s2 has a single parent student
Write a C++ program to explain the functionality of
Single level Inheritance [using student database]
class stdmarks : public student
#include<iostream.h> {
#include<conio.h> public:
class student int m1,m2,m3,tot;
{ float per;
public: void getmarks() void main()
int rno; { {
char name[25]; getdata(); stdmarks s1,s2;
void getdata() cout<<"Enter Marks out of 100 in all 3 subjects :- \t"; clrscr();
{ cin>>m1>>m2>>m3; s1.getmarks();
cout<<"Enter RollNo :- \t"; } s1.display();
cin>>rno; void display() s2.getmarks();
cout<<"Enter Name :- \t"; { s2.display();
cin>>name; tot=m1+m2+m3; getch();
} per=(float)tot/3; }
}; cout<<"Roll No : ” << rno<< “Name: ” <<name<<“ Total Marks: ”<<tot<<“ Percentage: “<<per;
} MAIN PROGRAM
};

BASE CLASS DERIVED


CLASS
Multiple Inheritance
It is the inheritance hierarchy wherein one derived class inherits
from multiple base class(es)
Multiple Inheritance
Write a C++ program to explain the functionality of Multiple
Inheritance [Calc. of area
DERIVEDand
CLASS perimeter of an rectangle]
/* Rectangle class is derived from classes Area and Perimeter. */
class Rectangle : public Area, public Perimeter
#include <iostream.h> {
#include <conio.h> private:
class Area float length, breadth;
{ public: void main()
public: Rectangle(){length=0.0; breadth=0.0; } {
float area_calc(float l,float b) void get_data( ) Rectangle r;
{ { r.get_data();
return l*b; cout<<"Enter length: "; cout<<“Area= ”<<r.area_derived();
} cin>>length; cout<<“Perimeter = "<<r.peri_derived();
}; cout<<"Enter breadth: "; getch();
class Perimeter cin>>breadth; }
{ }
public: float area_derived()
float peri_calc(float l,float b) { MAIN PROGRAM
{ /* Calls area_calc() of class Area */
return 2*(l+b); return Area::area_calc(length,breadth);
} }
}; float peri_derived()
{
/* Calls peri_calc() function of class Perimeter */
BASE CLASSES return Perimeter::peri_calc(length,breadth);
}
Inheritance Visibility Modes:

There are visibility modes to specify that in which


mode you are deriving the another class from the
already existing base class. They are:
Private: when a base class is privately inherited by a derived class, 'public
members' of the base class become private members of the derived class
and therefore no member of base class is accessible to the objects of the
derived class.
Public: On the other hand, when the base class is publicly inherited, 'public
members' of the base class become public members of derived class and
therefore they are accessible to the objects of the derived class also.
Inheritance Visibility Modes:
Visibility Modifier: Protected
C++ provides a third visibility modifier, protected, which serve a little
more purpose in the inheritance. A member declared as protected is
accessible by the member functions within its class and any class
immediately derived from it.
Protected access modifier is similar to that of private access modifiers,
the difference is that the class member declared as Protected are
inaccessible outside the class but they can be accessed by any
subclass(derived class) of that class.
Inheritance Visibility Modes:

The below mentioned table summarizes how the visibility of members


undergo modifications when they are inherited:
Multilevel Inheritance
When the inheritance is such that, the class A serves as a base class for a derived class
B which in turn serves as a base class for the derived class C.
This type of inheritance is called ‘MULTILEVEL INHERITENCE’.
The class B is known as the ‘INTERMEDIATE BASE CLASS’ since it provides a link for the
inheritance between A and C. The chain ABC is called ‘INHERITENCE PATH’
Class A
{
//body
}
Class B : public A
{
//body
}
Class C : public B
{
//body
}
Write a C++ program to explain the functionality of
Multilevel Inheritance [using student database]
#include<iostream.h>
#include<conio.h> class result : public marks // derived from marks
class marks : public student // derived from
#include<string.h> {
student
class student // base class private:
{
{ int t;
protected:
private: float p;
int s1,s2,s3;
int rl; char div[10];
public:
char nm[20]; public:
void getmarks();
public: void process();
void putmarks();
void read(); void printresult();
};
void display(); };
};

DERIVED CLASS
BASE CLASS FIRST LEVEL DERIVED CLASS
SECOND LEVEL
Write a C++ program to explain the functionality of Multilevel
Inheritance [using student database]
void student::read()
{
cout<<"enter Roll no and Name "<<endl;
cin>>rl>>nm; void result::process() void main()
} { {
void student:: display() t= s1+s2+s3; result x;
{ p = t/3.0; clrscr();
cout <<"Roll NO:"<<rl<<endl; if (p>=60) x.read();
cout<<"name : "<<nm<<endl; strcpy(div,"first") x.getmarks();
} else if (p>=50) strcpy(div, "second"); x.process();
void marks ::getmarks() else if (p>=35) strcpy(div,"third"); x.display();
{ else strcpy(div,”FAIL”); x.putmarks();
cout<<"enter three subject marks "<<endl; } x.printresult();
cin>>s1>>s2>>s3; void result::printresult() getch();
} { }
void marks ::putmarks() cout<<"total = "<<t<<endl;
{ cout<<"per = "<<p<<endl;
cout <<"subject 1:"<<s1<<endl; cout<<"div = "<<div<<endl; MAIN PROGRAM
cout<<" subject 2 : "<<s2<<endl; }
cout <<"subject 3:"<<s3<<endl;
}

FUNCTION
DEFINITIONS
Hierarchical Inheritance
It is the inheritance hierarchy wherein multiple subclasses inherit from
one base class.
Write a C++ program to explain the functionality of Hierarchical
Inheritance [Calc. of area of polygons]

#include <iostream.h>
class Polygon class Triangle: public Polygon
{ { void main ()
protected: public: {
int width, height; int area () Rectangle rect;
public: { return width * height / 2; } Triangle trgl;
void set_values (int a, int b) }; rect.set_values (4,5);
{ width=a; height=b;} trgl.set_values (4,5);
}; cout << rect.area() << '\n';
cout << trgl.area() << '\n';
class Rectangle: public Polygon getch();
{ }
public:
BASE CLASS int area ()
{ return width * height; } MAIN
}; PROGRAM

DERIVED
CLASSES
Hybrid Inheritance:
It is the inheritance hierarchy that reflects any legal combination of
other four types of inheritance.

Eg..Addition of sports data for student….using other class


Write a C++ program to explain the functionality of
Hybrid Inheritance [using student database]
class marks : public student // derived from
student
class sports // Independent class
#include<iostream.h> {
{
#include<conio.h> protected:
protected:
#include<string.h> int s1,s2,s3;
char grade;
class student // base class public:
public:
{ void getmarks();
void getgrade();
private: void putmarks();
};
int rl; };
char nm[20];
public:
DERIVED CLASS BASE CLASS FOR
void read(); FIRST LEVEL SECOND LEVEL
void display(); class result : public marks, public sports DERIVED CLASS
}; {
private:
int t;
float p;
BASE CLASS char div[10];
public:
void process();
void printresult();
};

DERIVED CLASS
Write a C++ program to explain the functionality of Hybrid
Inheritance [using student database]
void student::read() void sports:: getgrade()
{ {
cout<<"enter Roll no and Name "<<endl; cout<<“Grade in Sports: ”;
cin>>rl>>nm; cin>>grade; void main()
} } {
void student:: display() void result::process() result x;
{ { clrscr();
cout <<"Roll NO:"<<rl<<endl; t= s1+s2+s3; x.read();
cout<<"name : "<<nm<<endl; p = t/3.0; x.getmarks();
} if (p>=60) x.getgrade();
void marks ::getmarks() strcpy(div,"first") x.process();
{ else if (p>=50) strcpy(div, "second"); x.display();
cout<<"enter three subject marks "<<endl; else if (p>=35) strcpy(div,"third"); x.putmarks();
cin>>s1>>s2>>s3; else strcpy(div,”FAIL”); x.printresult();
} } getch();
void marks ::putmarks() void result::printresult() }
{ {
cout <<"subject 1:"<<s1<<endl; cout<<"total = "<<t<<endl; MAIN PROGRAM
cout<<" subject 2 : "<<s2<<endl; cout<<"per = "<<p<<endl;
cout <<"subject 3:"<<s3<<endl; cout<<“Sports Grade= "<<grade<<endl;
} cout<<"div = "<<div<<endl;
}
FUNCTION
DEFINITIONS
Virtual Base Class
The duplication of the inherited members can be avoided by making
common base class as the Virtual Base Class

Virtual base classes are used in inheritance in a way of preventing


multiple “instances” of a given class appearing in an inheritance
hierarchy when using multiple inheritances.

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.
Need for Virtual Base Classes:

Consider the situation where we have one class A .This class is A is inherited by
two other classes B and C. Both these class are inherited into another in a new
class D as shown in figure below.
 As we can see from the figure that data
members/function of class A are inherited
twice to class D, one through class B and
second through class C.
 When any data / function member of
class A is accessed by an object of class D,
ambiguity arises as to which data/function
member would be called? One inherited
through B or the other inherited through C.
 This confuses compiler and it displays error.
Resolving this Ambiguity
Syntax 1:
To resolve this ambiguity when class B : virtual public A
class A is inherited in both {
};
class B and class C, it is
declared as virtual base class Syntax 2:
by placing a keyword virtual. class C : public virtual A
{
};
Abstract Class
Sometimes implementation of all function cannot be provided in a base class
because programmer doesn’t know the implementation. Such a class is called
abstract class. 
Sometimes, when we have partial set of implementation of methods in a class. For
example, consider a class have four methods. Out of four methods, we have an
implementation of two methods and we need derived class to implement other
two methods. In these kind of situations, abstract class is used.
Eg. Let Shape be a base class. We cannot provide implementation of function
draw() in Shape, but we know every derived class must have implementation of
draw().
Example of Abstract Class class DerivedClass : public BaseClass
#include<iostream.h> {
#include<conio.h> public:
class BaseClass //Abstract class void Display1()
{ {
public: cout<<"\n\tThis is Display1() method of Derived Class";
virtual void Display1()=0; //Pure virtual function or abstract function }
virtual void Display2()=0; //Pure virtual function or abstract function void Display2()
void Display3() {
{ cout<<"\n\tThis is Display2() method of Derived Class";
cout<<"\n\tThis is Display3() method of Base Class"; }
} };
};

void main()
{
DerivedClass D;
D.Display1(); // This will invoke Display1() method of Derived Class
D.Display2(); // This will invoke Display2() method of Derived Class
D.Display3(); // This will invoke Display3() method of Base Class
}

Output :
This is Display1() method of Derived Class
This is Display2() method of Derived Class
This is Display3() method of Base Class
Pure virtual function & Abstract Class
• A virtual function will become pure virtual
function when you append "=0" at the end of
declaration of virtual function.
• A class with at least one pure virtual function is
called abstract class.
• Pure virtual function is also known as abstract
function.
• A pure virtual function (or abstract function) in
C++ is a virtual function for which we don’t have
implementation, we only declare it. A pure
virtual function is declared by assigning 0 in
declaration.
Abstract function & Abstract Class

Rules for Abstract Classes & Functions:


An object of abstract class cannot be created b'coz it has partial
implementation of methods.
When a class is not used for creating objects, it is called as abstract class.
Abstract class can act only as base class.
Abstract function doesn't have body.
We must implement all abstract functions in derived class.
Run-time / Late / Dynamic binding
Binding means link between a function call and the real function that is executed when a function is called.
There are two types of binding :-
i) Compile-time or early or static binding
ii) Run-time or late or dynamic binding
In early binding, the information pertaining to various overloaded member function is to be given to the
compiler while compiling.
Deciding a function call at compile time is called static binding.
Deciding a function call at run time is called dynamic binding.
It permits suspension of the decision of choosing a suitable member function until run time that is the
reason it’s called late binding

There are two types of polymorphism:


i) Run-time polymorphism (Virtual Function)
ii) Compile-time polymorphism (Function Overloading & Operator Overloading)
Run Time Polymorphism
Run time polymorphic features can be
incorporated using the virtual functions.
Virtual functions is one of advanced class use_defined_name
{
features of OOP by meaning it is a function
private:
that does not really exist but it appears public:
real in some parts of a program. virtual return_type function_name1 (arguments);
virtual return_type function_name2(arguments);
To make a member function virtual, the virtual return_type function_name3( arguments);
keyword virtual is used at the time of ------------------
declaration of the function };
Run Time Polymorphism[contd.]
The keyword virtual precedes the
return type of the function name. class point
{
Int x ;
Remember that the keyword virtual Int y ;
public:
should not be repeated in the virtual void display ( );
definition if the definition occurs };
void point: : display ( ) //function definition
outside the class declaration. {
Function Body
}
The use of a function specifier virtual in
the function definition is invalid
Write a C++ program to find the areas of triangle,
square and circle using the concept of virtual
function class triangle : public shape
#include <iostream.h> {
# include <conio.h> public:
class shape {
void show_area(void)
{
protected: cout << "Triangle with height ";
double x, y; cout << x << " and base " << y;
cout << " has an area of ";
public:
cout << x * 0.5 * y << ".\n";
void set_dim(double i=0, double j=0) }
{ };
x = i;
class square : public Shape
y = j; {
} public:
void show_area(void)
virtual void show_area(void) {
{ cout << "Square with dimensions ";
cout << x << "x" << y;
cout << "No area computation defined ";
cout << " has an area of ";
cout << "for this class.\n"; cout << x * y << ".\n";
} }
}; };
Write a C++ program to find the areas of triangle,
square and circle using the concept of virtual function
void main()
{
shape *p;
triangle t;
class circle : public shape square s;
{ circle c;
p = &t;
public: p->set_dim(10.0, 5.0);
void show_area(void) p->show_area();
p = &s;
{ p->set_dim(10.0, 10.0);
cout << "Circle with radius "; p->show_area();
p = &c;
cout << x; p->set_dim(10.0);
cout << " has an area of "; p->show_area();
}
cout << 3.14 * x * x;
}
};

You might also like