Unit III
Unit III
Unit III
TEXT BOOK
1. Ashok N Kamthane, “Object Oriented Programming with ANSI
and Turbo C++”, Pearson Education Publications, 2006.
#include<iostream.h>
#include<conio.h>
class number
{
public:
int X;
int Y;
number() {}
number (int j, int k)
{
X=j;
Y=k;
• }
number operator +(number D)
{
number T;
T.X=X+D.X;
T.Y=Y+D.Y;
Return T;
}
void show()
{
cout<<”\n X=”<<”\n Y=”<<Y;
}
};
void main()
{
clrscr();
number A(2,3) ,B(4,5),C;
A.show();
B.show();
C=A+B;
C.show();
}
3.2 Overloading Unary Operators
• In this type the left hand operand of (=) equal sign if always
the class type. The right hand operand is always basic type.
• The Conversion can be done by the compiler with the helpof
build routine or by applying type casting.
• It uses constructors for changing the Basic type to class type.
Example:
#include<iostream.h>
#include<conio.h>
class data
{
int x ;
float f;
public:
data( )
{
x=0; f=0;
}
data(float m)
{
x=2;
f=m;
}
void show( )
{
cout<<x<<f;
}
};
int main ( )
{
data= z
z=1;
z.show( );
z= 2.5
z.show( );
}
3.5.2 Conversion from class type – Basic data
type
Example:
• Write a program to derive a class publicly from base
class.declare the base class with its member under public
section.
#include<iostream.h>
#include<conio.h>
Class A
{
Public:
Int X;
};
Class B:public A
{
Public:
Int Y;
};
void main()
{
clrscr();
B b;
b.x=20;
b.y=10;
count<<”\n member of A:”<<b.x;
count<<”\n member of B:”<<b.y;
}
3.6.3 Private inheritance
• The object of privately derived class cannot access the public
members of the base class directly.
• The member function are used to access the member of the base
class.
Example:
• Write a program to derive a class privately. Declare the member
of base class under public section.
#include<iostream.h>
#include<conio.h>
class A
{
public:
int x;
};
Class B:private A
{
Public:
Int y;
B()
{
X=20;
Y=40;
}
void show()
{
cout<<”\n x=”<<x;
cout<<”\n y=”<<y;
}
};
void main()
{
clrscr();
B b;
b.show();
}
3.6 4 Protected data with private inheritance
{
int e;
public:
void get()
{
cout<<e<<z;
}
};
void main()
{
E e1;
e1.getdata();
e1.display();
e1.get();
e1.put();
}
3.11 Multilevel inheritance
• When a class is from another derived class that it the derived
class act is a base class.
• This type of inheritance is known as multilevel inheritance.
Example:
#include<iostream.h>
#include<conio.h>
class A1
{
protected :
int age;
char name[20];
};
void put()
{
cout<<age<<name;
cout<<height<<weight;
cout<<sex;
}
};
void main()
{
A3.x;
x.get();
x.put();
}
class A2:public A1
{
protected:
float height;
float weight;
};
class A3:publc A2
{
protected:
char sex;
public:
void get()
{
cin>>age>>name;
cin>>height>t>weight;
cin>>sex;
}
3.12 Hybrid Inheritance