Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Inheritance -Virtual Base Class

Inheritance -Virtual Base Class-c++

Uploaded by

sophin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Inheritance -Virtual Base Class

Inheritance -Virtual Base Class-c++

Uploaded by

sophin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

INHERITANCE: .

 The mechanism of deriving a new class from an old one is called inheritance or
derivation.
 The old class is referred to as the base class and the new one is called the derived
class or sub class.
 The derived class inherits some or all of the characteristics from the base class.
 A class can also inherit properties from more than one class or from more than
one level.
 Reusability is an important feature of OOP

A derived class can be defined by specifying its relationship with the base
class in addition to its own details.

class derived-class-name : visibility-mode base-class-name


{
………
………

The colon indicates that the derived class name is derived from the base-class-name.
the visibility mode is optional and if present, may be either private or protected or
public. The default is private. Visibility mode specifies whether the features of the
base class are privately derived or publicly derived.

class ABC : private XYZ

{
members of ABC;
};
//private derivation

class ABC:public XYZ

{
members of ABC;
};
//public derivation

class ABC:protected XYZ

// protected derivation

//members of ABC;

};
class ABC:XYZ //private by default

{
members of ABC;

};
When a base class is privately inherited by a derived class, public members of
the base class can only be accessed by the member functions of the derived
class.private membes of base class are inaccessible to the objects of the derived class
When a base class is protected inherited by a derived class, public members of
the base class can only be accessed by the member functions of the derived class.
Private membes of base class are inaccessible to the objects of the derived class. If
private members of base class are to be inherited to derived class then declare them as
protected
When the base class is publicly inherited, public members of the base class is
publicly inherited, public members of the base class become public members of the
derived class and therefore they are accessible to the objects of the derived class. In
both the cases, the private members are not inherited and therefore, the private
members of a base class will never become the members of its derived class
In inheritance, some of the base class data elements and member functions are
„inherited‟ into the derived class. We can add our own data and member functions and
thus extend the functionality of the base class. Inheritance, when used to modify and
extend the capability of the existing classes, becomes a very powerful tool for
incremental program development

Types of Inheritance:
1.Single Inheritance
2.Multi level Inheritance
3.Mutiple Inheritance
4.Hybrid inheritance
5. Hierarchical Inheritance.
1.SINGLE INHERITANCE:
one derived class inherits from only one base class. It is the most
simplest form of Inheritance. When a class inherits from a single base class,
it is known as single inheritance.

A / /Base class

B
//Derived class

Syntax:

#include<iostream.h>
class A
{
public:
int a,b;
void get()
{
cout<<"Enter any two Integer values"<<endl; cin>>a>>b;
}
};

class B:public A
{
int c;
public:
void add()
{
c=a+b;
cout<<a<<"+"<<b<<"="<<c;
}
};

int main()
{
B b;
b.get();
b.add();
}

Output:
Enter any two Integer
values 1 2
1+2=3

2. MULTILEVEL INHERITANCE: In this type of inheritance the derived class inherits


from a class, which in turn inherits from some other class. The Super class for one, is
sub class for the other.

The declaration for the same would be:


Class A
{
//body
}
Class B : public A
{
//body
}
Class C : public B
{
//body
}

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
‘ITNHERITENCE*PATH’ for
#include<iostream.h>
class A
{
public:
int a,b;
void get()
{
cout<<"Enter any two Integer values"<<endl; cin>>a>>b;
}
};

class B:public A
{
public:
int c;
void add()
{
c=a+b;
}
};
class C:public B
{
public:
void show()
{
cout<<a<<"+"<<b<<"="<<c;
}
};
int main()
{
C c;
c.get();
c.add();
c.show();
}

Output:
Enter any two Integer values 12 14
12+14=26

3.Multiple Inheritance:
 In this type of inheritance a single derived class may
inherit from two or more than two base classes.
 A class can inherit the attributes of two or more classes.
This mechanism is known as ‘MULTIPLE INHERITENCE’.
Multiple inheritance allows us to combine the features
of several existing classes as a starring point for defining
new classes.
It is like the child inheriting the physical feature of one
parent and the intelligence of another. The syntax of the
derived class is
 as follows:

A B

C
Syntax:
#include<iostream.h>
class A
{
public:
int a;
void getA()
{
cout<<"Enter an Integer value"<<endl;
cin>>a;
}
};
class B
{
public:
int b;
void getB()
{
cout<<"Enter an Integer value"<<endl;
cin>>b;
}
};
class C:public A,public B
{
public:
int c;
void add()
{
c=a+b;
cout<<a<<"+"<<b<<"="<<c<<endl;
}
};
int main()
{
C obj;
obj.getA();
obj.getB();
obj.add();
}

Output:

Enter an Integer
value 12
Enter an
Integer value 13
12+13=25

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:
 Consider the situation where we have one class A. This class A is
inherited by two other classes B and C. Both these classes are
inherited in a new class D. This is as shown in figure given below. In
dummy code form this is shown below :
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 ( ) ;
}

Pointers and arrays


(i) Pointers : pointer declaration
 A pointer is a memory variable that stores memory address. Pointers
"point to" a variable (memory) with a typed value by referencing that
variable, not by name, but by address.
 Pointers can have any name like any variable but it is always denoted by
‘*’ operator.
 When declaring, every variable occupies certain memory locations . It is
possible to access and display the address of memory location using ‘&’
Operator .
 Pointer variables stores the address of any type of variable. The pointer
variable and normal variable should be of any type. The pointer is
denoted by asterisk(*) symbol.

Features of pointers:
 Pointers save the memory space.
 Execution time with pointer is faster. Because data is Manipulated with
the address.
 The memory is accessed efficiently with the pointers.
 Pointers are used with data structures.
 A pointer declared to a base class could access the objects of derived
class.
Pointer declaration:
Pointer variable can be declared as,
datatype *var_name;

example:
int *x; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to character

Here int *x; is the integer pointer variable, and it informs the compiler that
it holds the address of any integer variable.
 The indirection operator(*) is also called the deference operator. When a
pointer is dereferenced, the value at that address stored by the pointer is
retrieved.
 Normal variables provide direct access to their own values but pointer in
directly accesses the value of a variable which it points.

 The indirection operator(*) is used in two ways.

 When a pointer is declared, the * indicates that it is a pointer, not a


normal variable.
 when a pointer is dereferenced, the indirection operator indicates
that the value at that memory location stored in the pointer is to be
accessed.
 The * operator normally used for multiple multiplication. The
compiler considers it depend on the context.
 The Ampersand ‘&’is the address operator and it represents the
address of the variable. The operator & immediately preceding the
bar variable returns the address of the variable.
Example program:
Live Demo
#include <iostream.h>

int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as
follows −
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointer to class
 A pointer is a variable that holds the address of another
data variable. The variable may be of any data type i.e.,
int, float or double.
 A class pointer is a pointer variable that stores address of an object of a
class.
 We can also define pointer to class. When defining
pointer to the class, the starting address of the member
variables can be accessed. Such pointers are called class
pointers.
 Example:
class book
{
char name[25];
char author[25];
int pages;
};

book *ptr;
using pointer to member variable is as follows:
ptr->name
ptr->author
ptr->pages
These three statements estimates the starting address of each member.

Example program1:
#include <iostream.h>
class Rectangle
{
private:
int length;
int breadth;
public:
Rectangle(int l, int b)
{
length=l;
breadth=b;
}
int getArea()
{
return 2*length*breadth;
}
};

int main()
{
// creating an object of Rectangle
Rectangle var1(5,2); // parameterized constrcutor

/* creating a pointer of Rectangle type &


assigning address of var1 to this pointer */
Rectangle* ptr = &var1;

/* calculating area of rectangle by using pointer


ptr to call the objects getArea() function */

int area = ptr->getArea();


cout<<"Area of rectangle is: "<<area;
return 0;
}

Output
Area of rectangle is: 20

As shown in the above diagram we have a class Rectangle with 2 data


members and 1 member function. We have also created an object of that
class named var1. Now we create a pointer variable *ptr of type Rectangle
and assign the address of the object var1 to this pointer variable. As shown
in the diagram the address of the object var1 is stored in the pointer
variable ptr.

Example program2:
include <iostream.h>

class Box {
public:

double Volume()
{
length=10.5;
breadth=20.0;
height=30.1;
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void)
{
Box Box1; // Declare box1
Box Box2; // Declare box2
Box *ptrBox; // Declare pointer to a class.

// Save the address of first object


ptrBox = &Box1;

// Now try to access a member using member access operator


cout << "Volume of Box1: " << ptrBox->Volume() << endl;

// Save the address of second object


ptrBox = &Box2;

// Now try to access a member using member access operator


cout << "Volume of Box2: " << ptrBox->Volume() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result −
Volume of Box1: 6300.1234
Volume of Box2: 6300.1234

 Pointer to object
 Like variables and class pointers, objects can also have an address. A
pointer can point to specified object.
 A variable that holds an address value is called a pointer variable or
simply pointer.
 Pointer can point to objects as well as to simple data types and arrays.
 sometimes we do not know, at the time that we write the program , how
many objects we want to create. when this is the case we can use new to
create objects while the program is running. new returns a pointer to an
unnamed objects.
Example:

class Bill
{
int qty;
float price;
};
--------
--------
Bill s; //object
Bill *ptr=s;
--------
---------
Example program:
#include <iostream.h>
#include <conio.h>
class Bill
{
int qty;
float price,amount;
public:
void getdata(int a, float b, float c)
{
qty=a;
price=b;
amount=c;
}
void show()
{
cout<<”Quantity :”<<qty<<”\n”;
cout<<”Price :”<< price<<”\n”;
cout<<”Amount :”<<amount<<”\n”;
}
};
void main()
{
clrscr();
Bill s; // object
Bill *ptr=&s; // pointer to object
ptr->getdata(45,10.25,45*10.25);
*ptr.show();
}
_________________________________________________
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
int rollno;
string name;
public:
student():rollno(0),name("")
{
}
student(int r, string n): rollno(r),name (n)
{
}
void get()
{
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
}
};
void main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}

This pointer
 In C++ programming, this is a keyword that refers to the
current instance of the class.
 Every object in C++ has access to its own address through an
important pointer called this pointer.
 The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the
invoking object.
 Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.

There can be 3 main usage of this keyword in C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexer

1) When local variable’s name is same as member’s name

#include<iostream>

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

Output:
x = 20
2) To return reference to the calling object

/* Reference to the calling object can be returned */


Test& Test::func ()
{
// Some processing
return *this;
}

When a reference to a local object is returned, the returned


reference can be used to chain function calls on a single
object.

#include<iostream>
using namespace std;

class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
Test &setX(int a)
{
x = a;
return *this;
}
Test &setY(int b)
{
y = b;
return *this;
}
void print()
{
cout << "x = " << x << " y = " << y << endl;
}
};

int main()
{
Test obj1(5, 5);

// Chained function calls. All calls modify the same


object
// as the same object is returned by reference
obj1.setX(10).setY(20);

obj1.print();
return 0;
}

Output:
x = 10 y = 20

Arrays in c++

 C++ provides a data structure, the array, which stores a fixed-size


sequential collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
 Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.
 A specific element in an array is accessed by an index.
 All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and
the number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare
a 10-element array called balance of type double, use this statement −
double balance[10];

Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement
as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ]. Following is an
example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array
with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of
their first element which is also called base index. Following is the pictorial
representaion of the same array we discussed above −

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the
index of the element within square brackets after the name of the array. For
example −
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to
salary variable. Following is an example, which will use all the above-mentioned
three concepts viz. declaration, assignment and accessing arrays –

Live Demo
#include <iostream.h>

#include <iomanip.h>

int main () {

int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0

for ( int i = 0; i < 10; i++ ) {


n[ i ] = i + 100;
// set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

return 0;
}
This program makes use of setw() function to format the output. When the above
code is compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109

C++ Arrays and Loops


string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}

Volvo
BMW
Ford
Mazda

C++ Multi-dimensional Arrays


C++ allows multidimensional arrays. Here is the general form of a multidimensional
array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer
array −
int threedim[5][10][4];

Two-Dimensional Arrays
 The simplest form of the multidimensional array is the two-dimensional array.
 A two-dimensional array is, in essence, a list of one-dimensional arrays.
 To declare a two-dimensional integer array of size x,y, you would write
something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++
identifier.
A two-dimensional array can be think as a table, which will have x number of rows
and y number of columns. A 2-dimensional array a, which contains three rows and
four columns can be shown as below −
Thus, every element in array a is identified by an element name of the form a[ i ]
[ j ], where a is the name of the array, and i and j are the subscripts that uniquely
identify each element in a.

Initializing Two-Dimensional Arrays


Multidimensioned arrays may be initialized by specifying bracketed values for each
row. Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in 2-dimensional array is accessed by using the subscripts, i.e., row
index and column index of the array. For example −
int val = a[2][3];
The above statement will take 4 th element from the 3rd row of the array. You can
verify it in the above digram.
Live Demo
#include <iostream>
using namespace std;

int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ ) {

cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}

return 0;
}

When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

C++ Array of Objects in c++


Array of Objects
 Like array of other user-defined data types, an array of type class can also be created.
 The array of type class contains the objects of the class as its individual elements.
 Thus, an array of a class type is also known as an array of objects.
 An array of objects is declared in the same way as an array of any built-in data type.

Syntax for Array of object

class class-name
{
datatype var1;
datatype var2;
----------
datatype varN;

method1();
method2();
----------
methodN();
};

class-name obj[ size ];

Example for Array of object

#include<iostream.h>
#include<conio.h>

class Employee
{
int Id;
char Name[25];
int Age;
long Salary;

public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"\n\tEnter Employee Id : ";
cin>>Id;

cout<<"\n\tEnter Employee Name : ";


cin>>Name;

cout<<"\n\tEnter Employee Age : ";


cin>>Age;

cout<<"\n\tEnter Employee Salary : ";


cin>>Salary;
}

void PutData() //Statement 2 : Defining PutData()


{
cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;
}

};

void main()
{

int i;

Employee E[3]; //Statement 3 : Creating Array of 3 Employees

for(i=0;i<3;i++)
{
cout<<"\nEnter details of "<<i+1<<" Employee";
E[i].GetData();
}

cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();

Output :

Enter details of 1 Employee


Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000

Enter details of 3 Employee


Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000

Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
WORKING With OPERATOR OVERLOADING
OPERATOR OVERLOADING:-
Operator overloading provides a flexible option for the creation of new
definations for most
of the C++ operators. We can overload all the C++ operators except the
following:
 Class members access operator (. , .*)
 Scope resolution operator (: :)
 Size operator(sizeof)
 Condition operator (? :)
Although the semantics of an operator can be extended, we can't change its
syntax, the
grammatical rules that govern its use such as the no of operands precedence
and associativety. For
example the multiplication operator will enjoy higher precedence than the
addition operator.
When an operator is overloaded, its original meaning is not lost. For example,
the operator +, which has been overloaded to add two vectors, can still be
used to add two integers.
DEFINING OPERATOR OVERLOADING:
To define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied . This is done with the
help of a special function
called operator function, which describes the task.
Syntax:-
return-type class-name :: operator op( arg-list)
{
function body
}
Where return type is the type of value returned by the specified operation and
op is the operator being overloaded. The op is preceded by the keyword
operator, operator op is the
function name.
operator functions must be either member function, or friend
function. A basic defference between them is that a friend function will have
only one argument for
unary operators and two for binary operators, This is because the object used
to invoke the member
function is passed implicitly and therefore is available for the member
functions. Arguments may be
either by value or by reference.
operator functions are declared in. the class using prototypes as follows:-
vector operator + (vector); /./ vector addition
vector operator-( ); //unary minus
friend vector operator + (vuelor, vector); // vector add
friend vector operator -(vector); // unary minus
vector operator - ( vector &a); // substraction
int operator = =(vector); //comparision
friend int operator = =(vector ,vrctor); // comparision
vector is a data type of class and may represent both magnitude and direction
or a series
of points called elements.
The process of overloading involves the following steps:-
1. Create a class that defines the data type that is used in the overloading
operation.
2. Declare the operator function operator op() in the public part of the class
3. It may be either a member function or friend function.
4. 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 opearators.
operator op(x);
for unary operator using friend function
operator op(x,y);
for binary operator usinf friend function.
Unary – operator overloading(using member function):
class abc
{
int m,n;
public:
abc()
{
m=8;
n=9;
}
void show()
{
cout<<m<<n;
}
operator -- ()
{
--m;
--n;
}
};
void main()
{
abc x;
x.show();
--x;
x.show();
}
Unary – - operator overloading(using friend function):
class abc
{
int m,n;
public:
abc()
{
m=8;
n=9;
}
void show()
{
cout<<m<<n;
}
friend operator --(abc &p);
};
operator -- (abc &p)
{
--p.m;
--p.n;
}
};
void main()
{
abc x;
x.show();
operator--(x);
x.show();
}
C++ has the ability to provide the operators with as special meaning for a data type. The mechanism
of giving such special meanings to an operator is known as operator overloading
To define an additional task to an operator, specify what it means in relation to
the class to which
the operator is applied. This is done with the help of a special function, called
operator function.
The process of overloading involves 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 operator op() in the public part of the class. It
may be a member
function or a friend function.
3. Here op is the operator to be overloaded.
4. Define the operator function to implement the required operations.

General Form:-
return-type classname :: operator op(arglist)
{
Function body
}
Applying overloading to operators means,
same operator in responding different manner. For example operator + can be
used as concatenate
operator as well as additional operator.
That is 2+3 means 5 (addition), where as
"2"+"3" means 23 (concatenation).
Performing many actions with a single operator is operator overloading. We
can assign a user
defined function to an operator. We can change function of an operator, but it
is not recommedned to
change the actual functions of operator. We can't create new operators using
this operatorloading.
Operator overloading concept can be applied in following two major areas
(Benefits)
1. Extension of usage of operators
2. Data conversions
Rules to be followed for operator overloading:-
1.Only existing operators can be overloaded.
2.Overloaded operators must have at least one operand that is of user defined
operators
3.We cannot change basic meaning of an operator.
4.Overloaded operator must follow minimum characteristics that of original
operator
5.When using binary operator overloading through member function, the left
hand operand must be
an object of relevant class
The number of arguments in the overloaded operator‟ s arguments list
depends
1. Operator function must be either member function or friend function.
2. If operator function is a friend function then it will have one argument
for unary operator& two arguments for binary operator
3. . If operator function is a member function then it will have Zero
argument for unary
4. operator & one arguments for binary operator

You might also like