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

Module III oops

Java module 3 notes

Uploaded by

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

Module III oops

Java module 3 notes

Uploaded by

9086ranjithan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Module III

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 difference
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.

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();
}

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.

INHERITANCE
Inheritance is one of the most important and useful characteristics of OOP. Literally inheritance means
adopting features by newly created thing from the existing one. The process of obtaining data members
and methods from one class to another class i.e., one class to acquire properties and characteristics
from another class is known as inheritance. In OOP inheritance can be defined as the as the process of
creating a new class from one or more existing classes. The existing class is known as base class or
parent class or super class where as newly created class is known as derived class or child class or sub
class. Inheritance provides a significant advantage in terms of code reusability. Consider the diagram
shown below

Base class Base class

derived class

Due to this the derived class B inherits the features of base class A. The derived
classes has allthe features of the base class and the programmer can choose to add
new features specific to the newly created derived class.
However, the derived class can also have its own features.
Inheritance makes the code reusable. Now the term reusability means, When we
inherit an existing class, all its methods and fields become available in the new class,
hence code is reused. that is the derived class object can access the base class
members also. However, the reverse of this is not true I,e the base class object can not
access the derived class members asthe base class is not aware of derivation of
derived class.(All the members of base class are inherited except the private
members.) Base class and Derived class
The existing class from which the derived class gets inherited is known as the base
class. It actsas a parent for its child class and all its properties I,e public and protected
members get inherited to its derived class.
A derived class can be defined by specifying its relationship with the base class in
addition to its own details i.e., members
The general form of defining a derived class is
class derived-class-name: access-specifier base-class-name
{
//members of the derived class
};

The access specifier determines how elements of the base class are inherited by the
derivedclass. (or)access specifier define how can the derived class access the Base
class members .
Here access is one of the three keywords: public, private and
protected. Base class accesibility is dependent on the visibility
mode of derived class.

Visibility modes can be classified into three categories

Modes of inheritance :
1. Public Mode: If we derive a sub class in public mode. Then the public
memberof
the
baseclass will become public in the derived class and the protected
members of the base class will become protected in derived class.
2. Protected Mode: If we derive a sub class in protected mode. Then both
public memberand protected members of the base class will become
protected in derived class.
3. Private Mode: If We derive a sub class in private mode. Then both
public member andprotected mem bers of the base class will
become private in derived class
In all cases, private members of a base class remain private to that base class.
It is important to understand that if the access specifier is private, public
members of the basebecome private members of the derived class. If access
specifier is not present, it is private by default.

List out visibility of inherited members in various categories of inheritance.

Derived class visibility


Base class visibility
Public derivation Private derivation Protected derivation
Private Not inherited Not inherited Not inherited
Protected Protected Private Protected
Public Public Private Protected

Explain protected access modifier for class members.

Protected:
This access modifier plays a key role in inheritance.
Protected members of the class can be accessed within the class and from
derived class but cannot be accessed from any other class or program.It works
like public for derived class and private for other programs

Explain types of inheritance with example.


Inheritance is the process, by which class can acquire the properties and
methods of anotherclass.
The mechanism of deriving a new class from an old class is
called inheritance.The new class is called derived class and old
class is called base class.
The derived class may have all the features of the base class and the
programmer can addnew features to the derived class.

Types of Inheritance:

 Single Inheritance If a class is derived from a single class then


it is called single inheritance.
Class B is derived from class A
A

 Multilevel Inheritance A class is derived from a class which is derived from


another class then it is called multilevel inheritance Here, class C is derived from
class B and class B is derived from class A, so it is called multilevel inheritance.

Multiple Inheritance

If a class is derived from more than one class then it is called multiple
inheritance.
Here, class C is derived from two
A B classes, class A andclass B.

Hierarchical Inheritance If one or more classes are derived from one


class then it
is called hierarchical inheritance.
Here, class B, class C and class D are derived
A

B C D
from class A.

Hybrid Inheritance It is a combination of any above inheritance


types.
That is either multiple or multilevel
A or hierarchical orany other
combination.
Here, class B and class C are derived
B C from class A andclass D is derived from
class B and class C.
class A, class B and class C is example of
D
Hierarchical Inheritance and class B,
class C and class D is example
of Multiple Inheritance so this hybrid inheritance iscombination of Hierarchical and Multiple
Inheritance.
Single inheritance: One derived class inherits from only one base class. The process in which a
derived class inherits traits from only one base class, is called single inheritance. In single
inheritance, there is only one base class and one derived class. The derived class inherits the
behavior and attributes of the base class. The derived class can add its own properties, ie data
members(variables) and functions. It can extend or use properties of the base class with out
any modification to the base class.

Syntax:
class base_class

{
};
class derived_class:visibility-mode base_class
{
};

Program to illustrate the concept of single inheritance


#include<iostream>
using namespace std; class person
{

protected:
char name[15]; int age;
};
class physique : public person
{

float height; float weight;


public:
void getdata() {
cout<<"Enter Name and Age :"; cin>>name>>age;
cout<<"Enter height and weight :"; cin>>height>>weight;

}
void show()
{
cout<<"\n Name: "<<name<<"\n"; cout<<" Age: "<<age<<" years"<<endl;
cout<<" Height: "<<height<<" Feet"<<endl; cout<<" Weight: "<<weight<<" kg."<<endl;;

}
};

int main() { physique p; p.getdata();


p.show();

return 0;
}
Multilevel inheritance
In this type of inheritance a single derived class may inherit from two or more than two base
classes. The process in which a derived class inherits traits from another derived class, is called
multilevel inheritance.
base class
syntax:
class A
intermedite class
{
……
derived class
};
class B:public A
{

……….
};
class C:public B
{
…….

};
Here, class B is derived from class A. Due to this inheritance, class B adopts the features of base
class A. Additionally, class B also contains its own features, Further, a new class, class c is
derived from class B, Due to this ,class c adopts the features of class B, as well as features of
class A.

Program to illustrate the concept of multilevel inheritance


#include<iostream>
using namespace std; class ONE { protected:
int n1;

};
class TWO: public ONE { protected:
int n2;
};
class THREE:public TWO { public:

void input() {
cout<<"Enter two integer numbers :"; cin>>n1>>n2;
}
void sum() { int sum=0; sum=n1+n2;
cout<<"Sum of "<<n1<<" + "<<n2<<"= "<<sum;

}
};
int main()
{
THREE t1;
t1.input();
t1.sum();
return 0;

}
Multiple inheritance
The process in which derived class inherits traits from several base classes, is called multiple
inheritance. In multiple inheritance, there is only one derived class and several base classes. we
declare the base classes and derived class as given.
Syntax:
class base_class1{
};

class base_class2{
};
class derived_class: visibility-mode base_class1,visibility-mode base-class2 {
};
Program to illustrate the concept of multiple inheritance #include<iostream>

using namespace std; class student {


int id;
char name[20]; public:
void getstudent() {
cout<<"Enter Student id and name : "; cin>>id>>name;

}
void putstudent() { cout<<"ID = "<<id<<endl;
cout<<"NAME = "<<name<<endl;
}
};

class marks { protected:


int m1,m2,m3; public:
void getmarks(){
cout<<"Enter marks of 3 subjects"; cin>>m1>>m2>>m3;
}
void putmarks() { cout<<"M1= "<<m1<<endl; cout<<"M2= "<<m2<<endl; cout<<"M3=
"<<m3<<endl;

} int main() {
result r;
}; r.getstudent();
r.getmarks();
class result:public student,public marks { int total; r.putstudent();
r.putmarks();
float avg; public:
r.show();
void show() { total=m1+m2+m3; avg=float(total)/3; return 0;
}
cout<<"TOTAL= "<<total<<endl; cout<<"AVERAGE= "<<avg<<endl; } };

Hierarchical Inheritance
In this type of inheritance,more than one sub class is inherited from a single base class.i,e more
than one derived class is created from a single base class.

syntax:
class base-class-name { data members; member functions;
};
class derived-class-name1:visibility mode base-class-name
{

data members; member functions;


};
class derived-class-name2:visibility mode base-class-name
{
data members; member functions;

}
Note: visibility mode can be either private,public or protected
Program to illustrate the concept of hierarchical inheritance #include<iostream>
using namespace std; class A {

public:
int x,y;
void getdata() {
cout<<"\n Enter the value for x and y:\n"; cin>>x>>y;
}

};
class B:public A { public:
void product() {
cout<<"\n product= "<<x*y;
}

};
class C:public A { public:
void sum() {
cout<<"\n sum= "<<x+y;
}
};
int main() { B obj1;
C obj2; obj1.getdata(); obj1.product(); obj2.getdata(); obj2.sum();
}
Hybrid inheritance: The combination of one or more type of inheritance happening together is
known as hybrid inheritance.
The following diagram explains the concept in better way.

In the diagram, the derivation of class B from class A is single inheritance.


The derivation of class C from class B , class D is multiple inheritance.
Program to illustrate the concept of hybrid inheritance #include<iostream>
using namespace std; class stu {

int id;
char name[20]; public:
void getstu() {
cout<<"Enter student id and Name:"; cin>>id>>name;
}

};
class marks:public stu { protected:
int m,p,c; public:
void getmarks() {
cout<<"Enter 3 subjects marks:"; cin>>m>>p>>c;

}
};
class sports { protected:
int spmarks; public:
void getsports() { cout<<"Enter sports marks: "; cin>>spmarks;
} int main()
}; {
result r;
class result:public marks,public sports { int tot;
r.getstu();
float avg; public: r.getmarks();
r.getsports();
void show() { tot=m+p+c; avg=tot/3.0;
r.show();
}
cout<<"Total= "<<tot<<endl; cout<<"Average= "<<avg<<endl; cout<<"Avg+sportsmarks=
"<<avg+spmarks;
}

};
Explain virtual base class with example.
It is used to prevent the duplication/ambiguity.
In hybrid inheritance child class has two direct parents which themselves have a common
baseclass.
So, the child class inherits the grandparent via two seperate paths. it is also called

as indirect parent class.


All the public and protected member of grandparent are inherited twice into child. We can stop
this duplication by making base class virtual.
A
The keywords virtual and public may be used in either order.

B C

D
If we use virtual base class, then it will inherit only single copy of member of base class to child
class.
//VIRTUAL BASE CLASSES
Figure: Multipath Inheritance
#include<iostream> using namespace std; class A {
protected:

int a;
};
class B : public virtual A { protected:
int main() {
int b; D obj;
}; obj.getdata();
obj.putdata();
class C : public virtual A { protected:
return 0;
int C;
}
};
class D : public B,C { int d;
public:
void getdata() {
cout<<"Enter values for a,b,c and d:"; cin>>a>>b>>c>>d;
}

void putdata(){
cout<<"a ="<<a<<"\t b ="<<b<<"\t c ="<<c<<"\t d ="<<d;
}
};
ADVANTAGES OF INHERITANCE

When a class inherits from another class, there are three benefits:
1. You can reuse the methods and data of the existing class .
The most frequent use of inheritance is for deriving classes using existing classes, which
provides reusability. The existing classes remain unchanged. By reusability, the development
time of software is reduced.
The same base classes can be used by a number of derived classes in class hierarchy.
2. You can extend the existing class by adding new data and new methods.
The derived classes extend the properties of base classes to generate more dominant objects.
When a class is derived from more than one class, all the derived classes have similar properties
to those of base classes.
3. You can modify the existing class by overloading its methods with your own
implementations

DISADVANTAGES OF INHERITANCE
1. Though object -oriented programming is frequently propagandized as an answer for
complicated projects, inappropriate use of inheritance makes programs more
complicated.
2. Invoking member functions using objects creates more compiler overheads.
3. In class hierarchy, various data elements remain unused, and the memory allocated
to them is not utilized.

You might also like