[go: up one dir, main page]

0% found this document useful (0 votes)
17 views16 pages

Unary Operator+ For Adding Two Complex Numbers (Using Member Function)

Uploaded by

NAAC Data
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
0% found this document useful (0 votes)
17 views16 pages

Unary Operator+ For Adding Two Complex Numbers (Using Member Function)

Uploaded by

NAAC Data
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/ 16

Unary operator+ for adding two complex numbers (using member function)

class complex
{
float real,img;
public:
complex()
{
real=0;
img=0;
}
complex(float r,float i)
{
real=r;
img=i;
}
void show()
{
cout<<real<<”+i”<<img;
}
complex operator+(complex &p)
{
complex w;
w.real=real+q.real;
w.img=img+q.img;
return w;
}
};
void main()
{
complex s(3,4);
complex t(4,5);
complex m;
m=s+t;
s.show();
t.show();
m.show();
}
Unary operator+ for adding two complex numbers (using friend function)
class complex
{
float real,img;
public:
complex()
{
real=0;
img=0;
}
complex(float r,float i)
{
real=r;
img=i;
}
void show()
{
cout<<real<<”+i”<<img;
}
friend complex operator+(complex &p,complex &q);
};
complex operator+(complex &p,complex &q)
{
complex w;
w.real=p.real+q.real;
w.img=p.img+q.img;
return w;
}
};
void main()
{
complex s(3,4);complex t(4,5);
complex m;
m=operator+(s,t);
s.show();t.show();
m.show();
}

Overloading an operator does not change its basic meaning. For example assume the +
operator can be overloaded to subtract two objects. But the code becomes unreachable.
class integer
{
intx, y;
public:
int operator + ( ) ;
}
int integer: : operator + ( )
{
return (x-y) ;
}
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.

Table 7.2
Operator to Arguments passed to the Arguments passed to the Friend
Overload Member Function Function
Unary Operator No 1
Binary Operator 1 2
LECTURE-24

Type Conversions
In a mixed expression constants and variables are of different data types. The assignment operations
causes automatic type conversion between the operand as per certain rules.

The type of data to the right of an assignment operator is automatically converted to the data type of
variable on the left.

Consider the following example:


int x;
float y = 20.123;
x=y ;

This converts float variable y to an integer before its value assigned to x. The type conversion is
automatic as far as data types involved are built in types. We can also use the assignment operator in
case of objects to copy values of all data members of right hand object to the object on left hand. The
objects in this case are of same data type. But of objects are of different data types we must apply
conversion rules for assignment.

There are three types of situations that arise where data conversion are between incompatible types.
1. Conversion from built in type to class type.
2. Conversion from class type to built in type.
3. Conversion from one class type to another.

Basic to Class Type


A constructor was used to build a matrix object from an int type array. Similarly, we used another
constructor to build a string type object from a char* type variable. In these examples constructors
performed a defacto type conversion from the argument's type to the constructor's class type

Consider the following constructor:

string :: string (char*a)


{
length = strlen (a);
name=new char[len+1];
strcpy (name,a);
}

This constructor builds a string type object from a char* type variable a. The variables length and
name are data members of the class string. Once you define the
constructor in the class string, it can be used for conversion from char* type to string type.

Example
string si , s2;
char* namel = “Good Morning”;
char* name2 = “ STUDENTS” ;
s1 = string(namel);
s2 = name2;
The program statement

si = string (namel);

first converts name 1 from char* type to string type and then assigns the string type values to the
object s1. The statement

s2 = name2;

performs the same job by invoking the constructor implicitly.


Consider the following example
class time
{
int hours;
int minutes;
public:
time (int t) // constructor
{
hours = t / 60; //t is inputted in minutes
minutes = t % 60;
}
};

In the following conversion statements :

time Tl; //object Tl created


int period = 160;
Tl = period; //int to class type
The object Tl is created. The variable period of data type integer is converted into class type time by
invoking the constructor. After this conversion, the data member hours ofTl will have value 2 arid
minutes will have a value of 40 denoting 2 hours and 40 minutes.

Note that the constructors used for the type conversion take a single argument whose type is to be
converted.

In both the examples, the left-hand operand of = operator is always a class object. Hence, we can
also accomplish this conversion using an overloaded = operator.
LECTURE-25
Class to Basic Type
The constructor functions do not support conversion from a class to basic type. C++ allows us to
define a overloaded casting operator that convert a class type data to basic type. The general form of
an overloaded casting operator function, also referred to as a conversion function, is:
operator typename ( )
{
//Program statmerit .
}

This function converts a class type data to typename. For example, the operator double( ) converts a
class object to type double, in the following conversion function:
vector:: operator double ( )
{
double sum = 0 ;
for(int I = 0; ioize;
sum = sum + v[i] * v[i ] ; //scalar magnitude
return sqrt(sum);
}

The casting operator should satisfy the following conditions.


 It must be a class member.
 It must not specify a return type.
 It must not have any arguments. Since it is a member function, it is invoked
by the object and therefore, the values used for, Conversion inside the
function belongs to the object that invoked the function. As a result function
does not need an argument.

In the string example discussed earlier, we can convert the object string to char* as follows:
string:: operator char*( )
{
return (str) ;
}

One Class to Another Class Type


We have just seen data conversion techniques from a basic to class type and a class to basic type. But
sometimes we would like to convert one class data type to another class type.

Example
Obj1 = Obj2 ; //Obj1 and Obj2 are objects of different classes.
Objl is an object of class one and Obj2 is an object of class two. The class two type data is converted
to class one type data and the converted value is assigned to the Objl. Since the conversion takes
place from class two to class one, two is known as the source and one is known as the destination
class.
Such conversion between objects of different classes can be carried out by either a
constructor or a conversion function. Which form to use, depends upon where we want the type-
conversion function to be located, whether in the source class or in the destination class.
We studied that the casting operator function
Operator typename( )
Converts the class object of which it is a member to typename. The type name may be a built-in type
or a user defined one(another class type) . In the case of conversions between objects,
typename refers to the destination class. Therefore, when a class needs to be converted, a
casting operator function can be used. The conversion takes place in the source class and the result is
given to the destination class object.
Let us consider a single-argument constructor function which serves as an instruction for
converting the argument's type to the class type of which it is a member. The argument belongs to
the source class and is passed to the destination class for conversion. Therefore the conversion
constructor must be placed in the destination class.
Table 7.3

Conversion Conversion takes place in


Source class Destination class
Basic to class Not applicable Constructor
Class to Basic Casting operator Not applicable
Class to class Casting operator Constructor

When a conversion using a constructor is performed in the destination class, we must be able to
access the data members of the object sent (by the source class) as an argument. Since data members
of the source class are private, we must use special access functions in the source class to facilitate
its data flow to the destination class.

Consider the following example of an inventory of products in a store. One way of keeping record of
the details of the products is to record their code number, total items in the stock and the cost of each
item. Alternatively we could just specify the item code and the value of the item in the stock. The
following program uses classes and shows how to convert data of one type to another.

#include<iostream.h>
#include<conio.h>
class stock2;
class stock1
{
int code, item;
float price;
public:
stockl (int a, int b, float c)
{
code=a;
item=b;
price=c;
}
void disp( )
{
cout<<”code”<<code <<”\n”;
cout<<”Items”<<item <<”\n”;
cout<<”Price per item Rs . “<<price <<”\n”;
}
int getcode( )
{return code; }
int getitem( )
{return item; }
int getprice( )
{return price;}
operator float( )
{
return ( item*price );
}
};

class stock2
{
int code;
float val;
public:
stock2()
{
code=0; val=0;
}
stock2(int x, float y)
{
code=x; val=y;
}
void disp( )
{
cout<< “code”<<code << “\n”;
cout<< “Total Value Rs . “ <<val <<”\n”
}
stock2 (stockl p)
{
code=p . getcode ( ) ;
val=p.getitem( ) * p. getprice ( ) ;
}
};

void main ( )
{ '
Stockl il(101, 10,125.0);
Stock2 12;
float tot_val;
tot_val=i1 ;
i2=il ;
cout<<” Stock Details-stockl-type” <<”\n”;
i 1 . disp ( ) ;
cout<<” Stock value”<<”\n”;
cout<< tot_val<<”\n”;
cout<<” Stock Details-stock2-type”<< “\n”;
i2 .disp( ) ;
getch ( ) ;
}

You should get the following output.


Stock Details-stock1-type
code 101
Items 10
Price per item Rs. 125
Stock value
1250

Stock Details-stock2-type
code 10 1
Total Value Rs. 1250
LECTURE-26

Inheritance:

Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability.
The C++ classes can be used again in several ways. Once a class has been written and tested, it can
be adopted by another programmers. This is basically created by defining the new classes, reusing
the properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class
being defined "is" also an object of inherited class. The old class is called 'BASE' class and the new
one is called'DERIEVED'class.

Defining Derived Classes


A derived class is specified by defining its relationship with the base class in addition to its own
details. The general syntax of defining a derived class is as follows:

class d_classname : Access specifier baseclass name


{
__
__ // members of derived class
};
The colon indicates that the a-class name is derived from the base class name. The access specifier or
the visibility mode is optional and, if present, may be public, private or protected. By default it is
private. Visibility mode describes the status of derived features e.g.

class xyz //base class


{
members of xyz
};
class ABC : public xyz //public derivation
{
members of ABC
};
class ABC : XYZ //private derivation (by default)
{
members of ABC
};
In the 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 capabilities of the existing classes,
becomes a very powerful tool for incremental program development.

Single Inheritance
When a class inherits from a single base class, it is known as single inheritance. Following program
shows the single inheritance using public derivation.

#include<iostream.h>
#include<conio.h>
class worker
{
int age;
char name [10];
public:
void get ( );
};
void worker : : get ( )
{
cout <<”yout name please”
cin >> name;
cout <<”your age please” ;
cin >> age;
}
void worker :: show ( )
{
cout <<”In My name is :”<<name<<”In My age is :”<<age;
}
class manager :: public worker //derived class (publicly)
{
int now;
public:
void get ( ) ;
void show ( ) ;
};
void manager : : get ( )
{
worker : : get ( ) ; //the calling of base class input fn.
cout << “number of workers under you”;
cin >> now;
cin>>name>>age;
} ( if they were public )
void manager :: show ( )
{
worker :: show ( ); //calling of base class o/p fn.
cout <<“in No. of workers under me are: “ << now;
}
main ( )
{
clrscr ( ) ;
worker W1;
manager M1;
M1 .get ( );
M1.show ( ) ;
}
If you input the following to this program:
Your name please
Ravinder
Your age please
27
number of workers under you
30
Then the output will be as follows:
My name is : Ravinder
My age is : 27
No. of workers under me are : 30
The following program shows the single inheritance by private derivation.
#include<iostream.h>
#include<conio.h>
class worker //Base class declaration
{
int age;
char name [10] ;
public:
void get ( ) ;
void show ( ) ;
};
void worker : : get ( )
{
cout << “your name please” ;
cin >> name;
cout << “your age please”;
cin >>age;
}
void worker : show ( )
{
cout << “in my name is: “ <<name<< “in” << “my age is : “ <<age;
}
class manager : worker //Derived class (privately by default)
{
int now;
public:
void get ( ) ;
void show ( ) ;
};
void manager : : get ( )
{
worker : : get ( ); //calling the get function of base
cout << “number of worker under you”; class which is
cin >> now;
}
void manager : : show ( )
{
worker : : show ( ) ;
cout << “in no. of worker under me are : “ <<now;
}
main ( )
{
clrscr ( ) ;
worker wl ;
manager ml;
ml.get ( ) ;
ml.show ( );
}
The following program shows the single inheritance using protected derivation
#include<conio.h>
#include<iostream.h>
class worker //Base class declaration
{ protected:
int age; char name [20];
public:
void get ( );
void show ( );
};
void worker :: get ( )
{
cout >> “your name please”;
cin >> name;
cout << “your age please”;
cin >> age;
}
void worker :: show ( )
{
cout << “in my name is: “ << name << “in my age is “ <<age;
}
class manager:: protected worker // protected inheritance
{
int now;
public:
void get ( );
void show ( ) ;
};
void manager : : get ( )
{
cout << “please enter the name In”;
cin >> name;
cout<< “please enter the age In”; //Directly inputting the data
cin >> age; members of base class
cout << “ please enter the no. of workers under you:”;
cin >> now;
}
void manager : : show ( )

{
cout « "your name is : "«name«" and age is : "«age;
cout «"In no. of workers under your are : "«now;
main ( )
{
clrscr ( ) ;
manager ml;
ml.get ( ) ;
cout « "\n \n";
ml.show ( );
}

Making a Private Member Inheritable


Basically we have visibility modes to specify that in which mode you are deriving the another class
from the already existing base class. They are:

a. 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 the public members of the base class can be accessed by its own
objects using the dot operator. The result is that we have no member of base
class that is accessible to the objects of the derived class.
b. 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.
c. Protected: C++ provides a third visibility modifier, protected, which serve a
little 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. It cannot be accessed by functions outside these two classes.

The below mentioned table summarizes how the visibility of members undergo modifications when
they are inherited

Base Class Visibility Derived Class Visibility


Public Private Protected
Private X X X
Public Public Private Protected
Protected Protected Private Protected

The private and protected members of a class can be accessed by:


a. A function i.e. friend of a class.
b. A member function of a class that is the friend of the class.
c. A member function of a derived class.
Student Activity
1. Define Inheritance. What is the inheritance mechanism in C++?
2. What are the advantage of Inheritance?
3. What should be the structure of a class when it has to be a base for other classes?
LECTURE-27

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 ‘ITNHERITENCE*PATH’ for
e.g.

A Base class

Inheritance path B Intermediate base


class

C Derived class

The declaration for the same would be:


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

This declaration will form the different levels of inheritance.

Following program exhibits the multilevel inheritance.

#include<iostream.h>
#include<conio.h>
class worker // Base class declaration
{
int age;
char name [20] ;
public;
void get( ) ;
void show( ) ;
}

void worker: get ( )


{
cout << “your name please” ;
cin >> name;
cout << “your age please” ;
}
void worker : : show ( )
{
cout << “In my name is : “ <<name<< “ In my age is : “ <<age;
}
class manager : public worker //Intermediate base class derived
{ //publicly from the base class
int now;
public:
void get ( ) ;
void show( ) ;
};
void manager :: get ( )
{
worker : :get () ; //calling get ( ) fn. of base class
cout << “no. of workers under you:”;
cin >> now;
}
void manager : : show ( )
{
worker : : show ( ) ; //calling show ( ) fn. of base class
cout << “In no. of workers under me are: “<< now;
}
class ceo: public manager //declaration of derived class
{ //publicly inherited from the
int nom; //intermediate base class
public:
void get ( ) ;
void show ( ) ;
};
void ceo : : get ( )
{
manager : : get ( ) ;
cout << “no. of managers under you are:”; cin >> nom;
}
void manager : : show ( )
{
cout << “In the no. of managers under me are: In”;
cout << “nom;
}
main ( )
{
clrscr ( ) ;
ceo cl ;
cl.get ( ) ; cout << “\n\n”;
cl.show ( ) ;
}
Worker

Private:
int age;
char name[20];

Protected:

Private:
int age;
char name[20];

Manager:Worker

Private:
int now;

Protected:

Public:
void get()
void show()
worker ::get()
worker ::get()

Ceo: Manager

Public:

Protected:

Public:
All the inherited
members

You might also like