Вы находитесь на странице: 1из 38

Basic Concepts of Object-Oriented Programming

Objects
Classes
Data Abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing

Object

Objects are basic run-time entities in an object-oriented system.


Objects are variable of type class.
Objects communicate with each other by sending messages.
Objects interact without having to know details of each others data or code.
The syntax for creating is
classname objectname;

Classes

The wrapping up of data and functions into a single unit is called class.
A class is a way to bind data and associated function together.
It allows data and functions to be hidden from external use.
The entire set of data and code of an object can be made user-defined type with the help of a
class.
A class is a collection of object of similar type.
Once a class has been defined, we can create any number of objects belonging to that class.
Classes are user-defined type and behave like the built-in types of a programming language.
The general form of class declaration is
class classname
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

The body of class is enclosed within braces and terminated by a semicolon.


These variables and functions are collectively called class members. The variables are known as
data members and the functions are known as member functions.
The keyword private and public are known as visibility modes.
The class members that have been declared as private can be accessed only within the class.
The public members can be accessed from outside the class.
By default the members of a class are private.
1

A simple class example


class item
{
int number;
float cost;
public:
void getdata(int a, float b);
void putdata();
};

Data Encapsulation

The wrapping up of data and functions into a single unit is known as encapsulation.
The data is not accessible to the outside world, and only those functions which are wrapped in
the class can access it.
The insulation of data from direct access by the program is called data hiding or information
hiding.

Data Abstraction

Abstraction refers to the act of representing essential features without including the
background details.
They encapsulate all the essential properties of the objects that are to be created.
Since the classes use the concept of data abstraction, they are known as Abstract Data
Types(ADT).

Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
The mechanism of deriving a new class from old class is called inheritance.
The new class will have the combined features of both the classes.
The old class is referred to as base class and the new class is referred to a derived class.
Inheritance provides the idea of reusability. We can add additional features to an existing class
without modifying it.
The general form of defining a derived class is :
class derived_class_name : visibility_mode base_classname
{
..
..
};

Polymorphism

Polymorphism means the ability to take more than one form i.e one name many forms.
Polymorphism refers to the property by which objects belonging to different classes are able to
respond to same message, but in different forms.
An operation may exhibit different behaviours in different instances. The behaviour depends
upon the type of data used in the operation.

Operator Overloading

The process of making an operator to exhibit different behaviours in different instances is


known as operator overloading.
The mechanism of giving special meaning to an operator is known as 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 operator function.

Syntax
return_type classname :: operator op(arglist)
{
---------------------}
Function Overloading

We can use same function name to perform different tasks is known as function overloading.
The function would perform different operations depending on the argument list (number
and type of arguments) in the function call.

Eg:
//Declarations
int add(int a , int b);
int add(float a ,float b);
//function calls
add(5,6);
add(6.5,9.2);

Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
Dynamic Binding means that the code associated with a given procedure call is not known until
the time of the call at run-time.
Dynamic Binding is also known as late binding.

Message Passing

An object oriented program consists of a set of object that communicates with each other.
Object communicates with one another by sending and receiving messages.
A message for an object is a request for execution of a procedure, and therefore will invoke a
function.
The receiving object generates the desired result.
Message passing involve specifying the name of the object, the name of the function and the
information to be sent.

Structures and Union:


Table 1 Difference between structure and union
Structure
A structure is defined with struct keyword.
All member of a structure can be manipulated
simultaneously
The size of a structure object is equal to the sum of
the individual sizes of the member object.
Structure members are allocated distinct memory
locations.

Union
A union is defined with union keyword.
The members of a union can be manipulated only
one at a time.
The size of the union object is equal to the size of
the largest member object.
Union members share common memory space for
their exclusive usage.

Enumerated data type

It provides the way for attaching names to number thereby increasing comprehensibility of the
code.
The enum keyword automatically enumerates a list of words by assigning them value 0,1,2 and
so on.
Eg. enum shape{circle,square,triangle};

new operator

We can initialize the memory using new operator.


Syntax
pointer-variabe = new data_type[value];
eg: int *p = new int[25];

delete operator

When a data object is no longer needed, it is destroyed to release the memory space for reuse
by using delete operator.
Syntax
delete pointer_variable;
eg: delete p;

Advantages of new operator over malloc() function

It automatically computes the size of the data object. We need not use the operator sizeof.
It automatically returns the correct pointer type, so that there is no need of using type cast.
It is possible to initialize the object while creating memory space.
Like any other operators, new and delete operator can be overloaded.

Function Prototyping

The prototype describes the function interface to the computer by giving details such as the
number and type of argument and the type of return values.
Declaration
return_type function_name(arglist);
eg: float volume(int x,int y);
Definition
return_type function_name(arglist)
{
-------}
4

inline function

An inline function is a function that is expanded inline when it is invoked.


The compiler replaces the function call with the corresponding function code.

Syntax
inline function_name()
{
----------}
Program For inline Function
#include<iostream.h>
inline float mul(int a,int b)
{
return(a*b);
}
void main()
{
cout<<mul(3,3);
}
OUTPUT
9

Function with Default Arguments

The function assigns a default value to the parameter which does not have a matching argument
in the function call.
Default values are specified when the function is declared.
Eg: float amount(float principal, int period=2);
Only trailing arguments will have default values and therefore we must add defaults from right
to left.
We cannot provide default value in the middle of the argument list.
eg: int mul(int i, int j=5,int k) // illegal

Program for Function with Default Arguments


#include<iostream.h>
void main()
{
void sum(float i,float j=10);
argument
sum(10.4,9.4);
sum(10);
}
void sum( float i,float j)
{
float k=i+j;
cout<<"k="<<k<<"\n";
}

//function declaration-default

Output
k=19.8
k=20
5

const arguments

Arguments in function can be declared as const


Eg: int length(const int x);
The qualifier tells the compiler that the function should not modify the const argument. The
compiler will generate an error when this condition is violated.

Recursion

Recursion is a situation where a function calls itself, i.e. one of the statements in the function
definition makes a call to the same function in which it is present.
Syntax
return_type function_name(arglist)
{
..
..
function_name();
//calling same function
..
..
}

Calculating Factorial of a number using recursive function.


#include<iostream.h>
int fact(int n)
{
if(n==0)
return 1;
return(n*fact(n-1)); //recursive functin call
}
void main()
{
int n;
cout<<"enter a number\n";
cin>>n;
cout<<"factorial is "<<fact(n);
}
Output
enter a number 3
factorial is 6

Function Overloading

Using same function name to perform different tasks is known as function overloading.
The function would perform different operations depending on the argument list (number and
type of arguments) in the function call.
Function Overloading is also known as function polymorphism.
Syntax
return_type function_name(arg1);
return_type function_name(arg1,arg2);
6

Eg:
//Declarations
int add(int a , int b);
int add(float a ,float b);
//function calls
add(5,6);
add(6.5,9.2);
A function call first matches the prototype having the same number and type of arguments and
then calls the appropriate function for execution. A best match must be unique. The function selection
involves following steps:
1. The compiler first tries to find an exact match in which the types of actual arguments are the
same, and use that function.
2. If an exact match is not found , the compiler uses the integral promotions to the actual
arguments such as
char to int
float to double , to find a match
3. When either of them fails, the compiler tries to use the built-in conversions to the actual
arguments and then uses the function whose match is unique.
4. If all of the steps fail, then the compiler will try user-defined conversions in combination with
integral promotions and built-in conversions to find a unique match.
Program for Function Overloading
#include<iostream.h>
double volume(double k,double l)
//function definition
{
return (k*l);
}
double volume(double j)
//function definition
{
return (j*j*j);
}
void main()
{
double volume(double k,double l);
//function declaration
double volume(double j);
//function declaration
cout<<"area of cylinder"<<volume(2.2,1.1); //function calling
cout<<"\narea of cube"<<volume(3.2);
}
Output
area of cylinder 2.42
area of cube 32.768

Defining Member Functions


Member function can be defined in two ways:
Outside the class definition.
Inside the class definition.
Defining Member Functions Outside the Class Definition

Member functions that are declared inside a class have to be defined separately outside the
class.
The general form of member function definition is
return_type class_name :: function_name(argument)
{
function body
}
The scope of the function is restricted to the class_name specified in the header line.
The symbol :: is called the scope resolution operator.

Characteristics of member functions:

Several different classes can use same function name. The membership label will resolve their
scope.
Member functions can access the private data of the class. A nonmember function cannot do
so(except friend function).
A member function can call another member function directly of same class, without using dot
operator.

Sample program for Defining function outside the class:


#include<iostream.h>
class a
{
int i;
public:
void show();
//function declaration
};
void a::show()
// defining member function outside the class
{
i=10;
cout<<"i="<< i;
}
void main()
{
a obja;
// creating object for cass a
obja.show();
//calling member function using object
}
OUTPUT
i=10
Defining Member Function Inside the Class Definition

The function declaration is replaced by the actual definition inside the class.
When a class is defined inside a class, it is treated as an inline function.
Therefore all restrictions and limitations that apply to inline function are also applicable here.
Only small functions can be defined inside the function.
8

Sample program for Defining function inside the class:


#include<iostream.h>
#include<conio.h>
class a
{
int i;
public:
void show()
// defining member function inside the class
{
i=10;
cout<<"i="<<i;
}
};
void main()
{
clrscr();
a obja;
// creating object for cass a
obja.show();
// calling member function using object
getch();
}
OUTPUT
i=10
Single program to define a function inside and outside the class
#include<iostream.h>
#include<conio.h>
class a
{
int i,k;
public:
void outside();
void inside()
{
k=19;
cout<<"\nk="<<k;
}
};
void a::outside()
{
i=10;
cout<<"\ni="<< i;
}
void main()
{
clrscr();
a obja;
obja.outside();
obja.inside();
}

// function declaration
// function definition inside the class

// defining member function outside the class

// creating object for class a


//calling member function using object

OUTPUT
i=10
k=19
9

Static Data Members

Static variable are used to maintain values common to the entire class.
It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
Only one copy of that member is created for the entire class and is shared by all objects of that
class
It is visible within the class, but its lifetime is entire program.

Syntax
static data_type variable;
Eg:
static int count;

Static Member Function

A member function that is declared static.


A static function can have access only to other static members declared in the same class.
A static member function can be called using class name instead of object as follows
class_name::function_name;

Syntax
Static function_name()
{
----------------------}

Friend Function

A function can be made friendly two or more classes, thereby allowing the function to have
access to private data of these classes.
The function declaration should be preceded by the keyword friend.
The function definition does not use either keyword friend or scope resolution operator ::
A function can be declared in any number of classes.

Syntax
friend return_type function_name(); //declaration
return_type function_name()
{

}
10

Characteristics of friend function

It is not in the scope of the class to which it has been declared as friend.
Since it is not in the scope of the class, it cannot be called using the object of that class.
It can be invoked like a normal function without the help of keyword.
Unlike member function, it cannot access the member names directly and has to use an object
name and dot operator with each member name.

A function friendly to two classes- Addition of two numbers using friend function
#include<iostream.h>
class b;
// class declaration
class a
{
int i;
public:
void setvalue(int a)
{
i=a;
}
friend int sum(a,b);
//friend function declaration
};
class b
{
int j;
public:
void setvalue(int a)
{
j=a;
}
friend int sum(a,b);
//friend function declaration
};
int sum(a a1,b b1)
//friend function definition
{
return(a1.i+b1.j);
}
void main()
{
int x,y;
a obja; // creating object for class a
b objb;
cout<<"enter two numbers";
cin>>x>>y;
obja.setvalue(x);
objb.setvalue(y);
cout<<"\nsum="<<sum(obja,objb); //calling friend function
}
Output
Enter two numbers 2 3
Sum=5

11

Constructor

A constructor is a special member function whose task is to initialize the object of its class.
It is special because its name is same as the class name.
The constructor is invoked whenever an object of its associated class is created.
It enables an object to initialize itself when it is created. This is known as automatic initialization
of objects.

Syntax:
class class_name
{

public:
classname(){}
};
Characteristics of Constructor

They should be declared in public section.


They are invoked automatically when an object is created.
They do not have return types, and cannot return values.
They cannot be inherited.
Constructor cannot be virtual.
We cannot refer to their addresses.
They make implicit calls to the operators new and delete when memory allocation is required.

Types of Constructor:

Default Constructor
Parameterized Constructor
Multiple Constructor
Constructor with Default Arguments
Copy Constructor
Dynamic Constructor

Default Constructor

A constructor which accepts no parameters is called default constructor.


When a constructor is not defined, the compiler supplies a default constructor.

Syntax
classname()
{

//Constructor Definition

12

Program for default constructor


#include<iostream.h>
#include<conio.h>
class sample
{
public:
sample()
{
cout<<"Default Constructor";
}
};
void main()
{
sample obj;
getch();
}
Output
Default Constructor
Parameterized Constructor

The constructor that can take arguments are called parameterized constructor.
It allows us to initialize the various data elements of different objects with different values when
they are created.

Syntax
class class_name
{

public:

class_name(arguments)
{

}
};
We must pass the initial values as arguments to the constructor function when an object is declared.
This is done in two ways:

By calling the constructor explicitly.


class_name object_name=class_name(0,100);

By calling constructor implicitly.


class_name object_name(38,10);
13

Program for parameterized Constructor


#include<iostream.h>
class a
{
int m,n;
public:
a(int x,int y)
//constructor definition
{
m=x;
n=y;
cout<<"\nm="<<m<<"\tn="<<n;
}
};
void main()
{
clrscr();
a obja1(10,20);
//constructor called impictly
a obja2=a(24,12);
//constructor called explictly
}
Output:
m=10 n=20
m=24 n=12
Multiple Constructor/Constructor Overloading

We can have multiple Constructors with same name in same class. The Constructors are varied
based on their argument list. This is also known as Constructor Overloading.

Syntax
class class_name
{

public:
class_name(){}
class_name(arg1){}
class_name(arg1,arg2){}
};
Program for implementation of constructor overloading
#include<iostream.h>
class a
{
int m,n;
public:
a()
//default constructor
{
m=0;
n=0;
cout<<"\nm="<<m<<"\tn="<<n;
}
a(int x)
{
m=x;
14

cout<<"\nm="<<m;
}
a(int x,int y)
//parameterized constructor
{
m=x;
n=y;
cout<<"\nm="<<m<<"\tn="<<n;
}
};
void main()
{
a obj1;
//invoking defualt constructor
a obj2(3);
a obj3(24,12);
//constructor called explictly
getch();
}
Output
m=0 n=0
m=3
m=24 n=12
Constructor with Default Arguments

It is possible to define constructor with default arguments.


Eg:- complex(float real, float imag=0) here the default value of imag is zero.

Program for implementation of constructor with Default Argument


#include<iostream.h>
class a
{
int m,n;
public:
a(int x,int y=3)
//constructor with default argument
{
m=x;
n=y;
cout<<"\nm="<<m<<"\tn="<<n;
}
};
void main()
{
clrscr();
a obja1(10,20);
a obja2(24);
//constructor will take default value for y
}
Output
m=10 n=20
m=24 n=3
15

Copy Constructor
Copy constructor is used to declare and initialize an object from another object.
For example
integer i2(i1);
integer i2=i1;

would define the object i1 and initialize it to the values of i1.

A copy constructor will takes reference to an object of the same class as itself as an argument.

Program for implementation of copy constructor


#include<iostream.h>
#include<conio.h>
class a
{
int m;
public:
a()
{
m=10;
cout<<"value initialized";
}
a(a & obj)
//copy constructor
{
cout<<"\nvalue copied ";
m=obj.m;
}
void display()
{
cout<<"\nm="<<m;
}
};
void main()
{
clrscr();
a obja1;
//constructor called
obja1.display();
a obja2(obja1);
//copy constructor called
obja2.display();
}
Output
value initialized
m=10
value copied
m=10
Dynamic Constructor

The constructor is used to allocate memory while creating objects.


This enable the system to allocate the right amount of memory for each object when the object
are not of the same size, results in saving memory.
Allocation of memory to object at the time of their construction is known as dynamic
construction of object.
16

Example program for Dynamic Constructor


#include<iostream.h>
#include<string.h>
class String
{
char *name;
char length;
public:
String(char *s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
cout<<"the given string is "<<name;
}
};
void main()
{
char *first;
cout<<"enter the string ";
cin>>first;
String name(first);
}
Output
Enter the string ravi
The given string is ravi
Destructor

Syntax:

A destructor is used to destroy the objects that have been created by a constructor.
Like constructor, the destructor is a member function whose name is the same as the class
name but is preceded by a ~ tilde symbol.
A destructor never takes any argument nor does it return any value.
It will be invoked implicitly by the compiler to clean up storage that is no longer accessible.
~class_name(){}

Program for implementation of Destructor


#include<iostream.h>
class a
{
public:
a()
//constructor definiiton
{
cout<<"\nconstructor";
}
~a()
//destructor definiton
{
cout<<"\ndestructor";
}
};
void main()
{
a obja1;
}
17

Output
constructor
destructor
Single Program for Constructor, Constructor Overloading, Parameterized Constructor with default
values, Copy Constructor and Destructor
#include<iostream.h>
class a
{
int m,n;
public:
a() //default constructor
{
m=10;
n=20;
}
a(int x,int y=10)
//parameterized constructor with default value
{
m=x;
n=y;
}
a(a & obj)
//copy constructor
{
m=obj.m;
n=obj.n;
}
void display()
{
cout<<"\nm="<<m;
cout<<"\tn="<<n;
}
~a()
{
cout<<"\tdestructor ";
}
};
void main()
{
a obja1;
//constructor called
a obja2(13,40);
a obja3(28);
a obja4(obja1);
//copy constructor called
obja1.display();
obja2.display();
obja3.display();
obja4.display();
}
Ouptut
m=10 n=20
m=13 n=40
m=28 n=10
m=10 n=20
destructor

destructor

destructor

destructor
18

Operator Overloading

The process of making an operator to exhibit different behaviours in different instances is known
as operator overloading.
The mechanism of giving special meaning to an operator is known as 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 operator function.
Syntax

return_type classname :: operator op(arglist)


{
----------}
Overloaded operator functions can be invoked by expressions such as
op x or x op ---- for unary operators
x op y ------ for binary operators

The process of overloading involves the following steps:

Create the class that defines the data type that is to be used in the overloading operation.
Declare the operator function using operator op() in the pubic part of the class. It may be either
a member function or a friend function.
Define the operator function to implement the required operators.

Operators which cannot be overloaded:

Class member access operators (. *)


Scope resolution operator (::)
Size of operator(sizeof)
Conditional operator (?:)

Operators which cannot be overloaded as friend:

Assignment operator =
Function call operator ()
Subscripting operator []
Class member access operator

Rules for Overloading Operators:

Only existing operator can be overloaded. New operator cannot be created.


The overloaded operator must have atleast one operand that is of user-defined type.
Overloaded operators follow the syntax rule of original operator. They cannot be overridden.
Some operators cannot be overloaded. ( refer above)
We cannot use friend function to overload certain operators. ( refer above)
Unary operator when overloaded by member function takes no argument and returns no value,
but when overloaded by means of a friend function takes one reference argument.
Binary operators overloaded by member function takes one explicit argument and those
overloaded through friend takes two explicit arguments.
19

Overloading Unary Operators

Unary operator when overloaded by member function takes no argument and returns no value,
but when overloaded by means of a friend function takes one reference argument.
Overloaded operator functions can be invoked by expressions such as
op x or x op

Program for overloading unary operator

A minus operator when used as unary takes one operand.


We know that the binary minus operator changes the sign of an operand when applied to an
basic data item.
Here we overload this operator so that it can be applied to an object should change the sign of
each of its data items.

#include<iostream.h>
class space
{
int x,y,z;
public:
void getdata(int a,int b, int c)
{
x=a;
y=b;
z=c;
}
void display()
{
cout<<"\nx="<<x;
cout<<"\ty="<<y;
cout<<"\tz="<<z;
}
void operator -()
{
x=-x;
y=-y;
z=-z;
}
};
void main()
{
space s;
s.getdata(10,20,-21);
s.display();
cout<<"\nafter activating operator -() function";
-s;
s.display();
}
Output:
x=10 y=20 z=-21
after activating operator () function
x=-10 y=-20 z=21
20

Overloading Unary Operators using Friend Function

Unary operator when overloaded by means of a friend function takes one reference argument.

Program for overloading unary operator using friend function

A minus operator when used as unary takes one operand.


We know that the binary minus operator changes the sign of an operand when applied to an
basic data item.
Here we overload this operator using friends so that it can be applied to an object should
change the sign of each of its data items.
#include<iostream.h>
class space
{
int x,y,z;
public:
void getdata(int a,int b, int c)
{
x=a;
y=b;
z=c;
}
void display()
{
cout<<"\nx="<<x;
cout<<"\ny="<<y;
cout<<"\nz="<<z;
}
friend void operator -(space &s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}
};
void main()
{
space s;
s.getdata(10,20,-21);
s.display();
cout<<"after activating operator -() function";
-s;
s.display();
}

Output:
x=10
y=20
z=-21
after activating operator () function
x=-10
y=-20
z=21
21

Overloading Binary Operators

Binary operators overloaded by member function takes one explicit argument and those
overloaded through friend takes two explicit arguments.

Program for overloading binary operator subtraction of complex number

We know that the binary minus operator is used to subtract the operand.
Here we overload this operator so that it can be applied to an object which in turn subtracts the
variables of the specific object.

#include<iostream.h>
class complex
{
float x,y;
public:
complex(){}
complex(float a, float b)
{
x=a;
y=b;
}
complex operator-(complex c)
{
complex temp;
temp.x=x-c.x;
temp.y=y-c.y;
return(temp);
}
void display()
{
cout<<x<<"+j"<<y<<"\n";
}
};
void main()
{
complex c1(2.4,6.3);
complex c2(1.2,4.2);
complex c3;
c3=c1-c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=c1-c2=";
c3.display();
}
Output
c1=2.4+j6.3
c2=1.2+j4.2
c3=c1-c2=1.2+j2.1

22

Overloading Binary Operator using Friend Function

The friend function can be used in place of member function for overloading binary operator,
the only difference being that a friend function requires two arguments to be explicitly passed
to it, while member function requires only one.

Program for overloading binary operator subtraction of complex number

We know that the binary minus operator is used to subtract the operand.
Here we overload this operator so that it can be applied to an object which in turn subtracts the
variables of the specific object.
#include<iostream.h>
class complex
{
float x,y;
public:
complex(){}
complex(float a, float b)
{
x=a;
y=b;
}
friend complex operator-(complex a,complex b)
{
complex temp;
temp.x=a.x-b.x;
temp.y=a.y-b.y;
return(temp);
}
void display()
{
cout<<x<<"+j"<<y<<"\n";
}
};
void main()
{
complex c1(2.4,6.3);
complex c2(1.2,4.2);
complex c3;
c3=c1-c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=c1-c2=";
c3.display();
}

Output
c1=2.4+j6.3
c2=1.2+j4.2
c3=c1-c2=1.2+j2.1
23

Type Conversion

It specifies conversion from one data type to another data.


The type of data to the right of an assignment operator is automatically converted to the type of
variable on the left for built in types
The type conversion is automatic as long as the data types involved are built in type.
Three types of data conversion arise between uncompatible types such as:

Conversion from basic type to class type


Conversion from class type to basic type
Conversion from one class type to another class type

Basic to class type


The conversion from basic to class type is easily accomplished by using constructors.
Eg
string::string(char *s)
{
length=strlen(a);
p=new cahr[length+1];
strcpy(p,a);
}
This constructor builds a string type object from a char* type variable a.
string s;
char* name=hello;
s=name;
Program conversion from basic type to class type
#include<iostream.h>
#include<string.h>
class String
{
char *name;
char length;
public:
String(char *s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
cout<<"the given string is "<<name;
}
};
void main()
{
char *first;
cout<<"enter the string ";
cin>>first;
String name(first);
}
Output
enter the string ravi
the given string is ravi
24

Class to Basic Type

The casting operator is used to convert a class type data to basic type.
Constructor function does not support this operation.
The general form of an overloaded casting operator function usually referred to as conversion, is

operator typename()
{
..
.
}
This function converts a class type data to typename.
For example, the operator double() converts a class object to type double.

Program conversion from basic type to class type


#include<iostream.h>
#include<math.h>
class sample
{
int x;
public:
operator double()
{
double sum=x;
return sqrt(sum);
}
};
void main()
{
sample s;
s.x=10;
double length =s;
cout<<the square root of 10=<<length;
}
Output
the square root of 10=3.162278;

In the above program the operator function converts an integer to double value.

The casting operator function should satisfy the following conditions:

It must be a class member


It must not specify a return type
It must not have any arguments

One Class to another Class Type

It converts one object type to another object type.


Example
objX=objY;
objX is an object of class X and objY is an object of class y.
25

The class Y type data is converted to class X type data.


Since the conversion takes from class Y to class X, Y is known as the source class and X is known
as the destination class.
Both conversion function and constructor is used to perform conversion between objects of
different classes.
Program for data type conversion
#include<iostream.h>
class a
{
public:
int x,y;
a(int a,int b)
{
x=a;
y=b;
}
operator float()
//casting operator
{
return(x*y);
}
};
class b
{
public:
int x;
b(){}
b(a obj)
//constructor for type conversion
{
x=obj.x+obj.y;
}
};
void main()
{
a obja(10,20);
b objb;
float z;
z=obja;
objb=obja;
cout<<"the multiplication of two numbers is "<<z;
cout<<"the addition of two numbers is "<<objb.x;
}

Output
The multiplication of two numbers is 200
The addition of two numbers is 30
Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
The mechanism of deriving a new class from old class is called inheritance.
The new class will have the combined features of both the classes.
26

The old class is referred to as base class and the new class is referred to as derived class.
Inheritance provides the idea of reusability. We can add additional features to an existing class
without modifying it.
The general form of defining a derived class is :
class derived_class_name : visibility_mode base_classname
{
..
..
};

Types of Inheritance

Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance

Single Inheritance

The process of deriving a new class from only one base class is called single Inheritance.
A

Syntax

BASE CLASS
DERIVED CLASS

class A{.};
class B:public A{};

The class B is derived from the base class A.

Program for Single Inheritance


#include<iostream.h>
class a
{
public:
void displaya()
{
cout<<"\nbase class";
}
};
class b:public a
{
public:
void displayb()
{
cout<<"\nderived class";
}
};
27

void main()
{
b objb;
objb.displaya();
objb.displayb();
}
Output
base class
derived class
Multiple Inheritance

A class can inherit the properties of more than one class.


A class derived from more than one base class is called Multiple Inheritance.
A

Syntax
class A{}
C
class B{..}
class C:public A,public B{.};
class C is derived from two base classes A and B.

Program for Multiple Inheritance


#include<iostream.h>
class a
{
public:
void displaya()
{
cout<<"\nbase class a";
}
};
class b
{
public:
void displayb()
{
cout<<"\nbase class b";
}
};
class c:public a,public b
{
public:
void displayc()
{
cout<<"\nderived class c";
}
};
28

void main()
{
c objc;
objc.displaya();
objc.displayb();
objc.displayc();
}
Output :
base class a
base class b
derived class c
Multilevel Inheritance
The mechanism of deriving a class from the derived class is known as multilevel inheritance.

BASE CLASS

INTERMEDIATE CLASS

DERIVED CLASS

The class A serves as a base class for the derived class B, which in turn serves as a base class for
the derived class C.
The class B is known as intermediate base class, since it provides the link between class A and C.
The chain ABC is known as inheritance path.
Syntax:
class A{};
class B:public A{..};
class C:public B{...};

Program for Multilevel Inheritance


#include<iostream.h>
class a
{
public:
void displaya()
{
cout<<"\nbase class a";
}
};
class b:public a
{
public:
29

void displayb()
{
cout<<"\nintermediate class b";
}
};
class c:public b
{
public:
void displayc()
{
cout<<"\nderived class c";
}
};
void main()
{
c objc;
objc.displaya();
objc.displayb();
objc.displayc();
Hierarchical Inheritance
The properties of one class can be inherited by more than one class. This process is known as
Hierarchical Inheritance.
A single class serves as a base class for two or more derived classes.
Syntax
class A{};
class B:public A{..};
class C:public A{...};

Program for Hierarchical Inheritance


#include<iostream.h>
class a
{
public:
void displaya()
{
cout<<"\nbase class a";
}
};
class b:public a
{
public:
void displayb()
{
cout<<"\nderived class b";
}
};
class c:public a
{
public:
30

void displayc()
{
cout<<"\nderived class c";
}
};
void main()
{
b objb;
objb.displaya();
objb.displayb();
c objc;
objc.displaya();
objc.displayc();
}
Output :
base class a
derived class b
base class a
derived class c
Hybrid Inheritance

Hybrid inheritance is defined as the combination of two or more types of inheritance to design a
program.
Syntax
A
class A{};
class B:public A{..};
#include<iostream.h>
class a
class C{};
B
C
{
class D:public B, public C{.}
public:
void displaya()
{
cout<<"\nbase class a";
D
}
};
class b:public a
{
public:
void displayb()
{
cout<<"\nintermediate class b";
}
};
class c
{
public:
void displayc()
{
cout<<"\nbase class c";
}
};
31

class d:public b,public c


{
public:
void displayd()
{
cout<<"\nderived class d";
}
};
void main()
{
d objd;
objd.displaya();
objd.displayb();
objd.displayc();
objd.displayd();
}
Output :
base class a
intermediate class b
base class c
derived class d
Templates

Templates allow us to define generic classes and functions and thus provide support for generic
programming.
Generic programming is an approach where generic types are used as parameters in algorithms
so that they work for a variety of suitable data structures.
Template allows the construction of a family of template functions and classes to perform the
same operation on different data types.
When an object of a specific type is defined for actual use, the template definition for that class
is substituted with the required data type.

Class Template

Templates allow us to define generic classes. Classes can be declared to operate on different
data types.
The class template models a generic class which supports similar operations for different data
types.
The general format for class template is
template<class T>
class class_name
{
.
// class member with type T
.
};

The prefix template<class T> tells the compiler that we are going to declare a template and use
T as a type name in the declaration.
32

A class created for template is called template class.


The syntax for defining an object of a template class is
class_name<type> object_name(arglist);

Example Program Class Templates


#include<iostream.h>
template<class T>
class test
{
T a;
public:
test( T x)
{
a=x;
}
void show()
{
cout<<"\ta="<<a;
}
};
void main()
{
test<int>tobj1(3);
test<float>tobj2(3.2);
test<char>tobj3('w');
tobj1.show();
tobj2.show();
tobj3.show();
}
Output
a=3

a=3.2 a=w

Class Templates with Multiple Parameters

We can use more than one data type in a class template.


They are declared as a comma-separated list within the template specification.
Syntax
template<class T1, class T2,..>
class class_name
{
------------------};

The syntax for defining an object of a template class is


class_name<type,type,> object_name(arg1,arg2,..);

33

Program for Two Generic Data Types in a Class Definition


#include<iostream.h>
template<class T1,class T2>
class test
{
T1 a;
T2 b;
public:
test( T1 x,T2 y)
{
a=x;
b=y;
}
void show()
{
cout<<"\na="<<a<<"\tb="<<b;
}
};
void main()
{
test<int,float>tobj1(3,5.4);
test<float,char>tobj2(3.2,'t');
tobj1.show();
tobj2.show();
}
Output
a=3
a=3.2

b=5.4
b=t

Templates with Default Data Types:


As we specify default values for functions arguments, we can also specify default types for the
template class data types.
Syntax
template<class t1=data_type, class t2=data_type>
class class_name
{
------------------};
Example Program
#include<iostream.h>
template<class T1,class T2=int>
class test
{
T1 a;
T2 b;
public:
test( T1 x,T2 y)
{
34

a=x;
b=y;
}
void show()
{
cout<<"\na="<<a<<"\tb="<<b;
}
};
void main()
{
test<int,float>tobj1(3,5.4);
test<>tobj2('t',76);
tobj1.show();
tobj2.show();
}
Output
a=3
b=5.4
a=t
b=76
Function Templates

Function Templates is used to create a family of functions with different argument types.
The general form of function template is:
template<class T >
return_type function_name(arguments of type T)
{
..
}
Function Template syntax is similar to that of class template except that we are defining
functions instead of classes.
We must use the template parameter T in the function body and in its argument list when
necessary.

Example Program Function Templates


Program to display data of different data type using single function
#include<iostream.h>
template<class T1>
void display(T1 x)
{
cout<<"\tx="<<x;
}
void main()
{
display(12);
display(23.45);
display('c');
}
Output
x=12 x=23.45 x=c

35

Program to swap two values of different data types using single function
#include<iostream.h>
template<class T>
void swap(T &x,T &y)
{
T temp=x;
x=y;
y=temp;
}
void main()
{
int a,b;
char c,d;
float e,f;
cout<<"\nenter two integers a and b";
cin>>a>>b;
cout<<"\nenter two characters c and d";
cin>>c>>d;
cout<<"\nenter two float point numbers e and f";
cin>>e>>f;
swap(a, b);
swap(c,d);
swap(e,f);
cout<<"\nthe values after swapping";
cout<<"a="<<a<<"\tb="<<b;
cout<<"\nc="<<c<<"\td="<<d;
cout<<"\ne="<<e<<"\tf="<<f;
}
Output
enter two integers a and b 5 9
enter two characters c and d a c
enter two float point numbers e and f
Overloading of Template Functions
A template function can be overloaded either by template functions or ordinary functions of its
name.
Overloading resolution is accomplished as follows:
1. Call an ordinary function that has an exact match.
2. Call a template function that could be created with an exact match.
3. Try normal overloading resolution to ordinary functions and call the one that
matches.
An error is generated if no match found.
No automatic conversions are applied to arguments on template functions.
#include<iostream.h>
template<class T1>
void display(T1 x)
{
cout<<"\ntemplate display
}
void display(int x)
{

x="<<x;

36

cout<<"\nexplict display
}
void main()
{
display(12);
display(23.45);
display('c');
}

x="<<x;

Output
explict display
template display
template display

x=12
x=23.45
x=c

Member Function Templates


It is possible to define the function outside the class using Member Function Templates.
Syntax
template<class T>
return_type class_name<T>::function_name(arglist)
{

}
Example Program
#include<iostream.h>
template<class T>
class sample
{
T x;
public:
void display(T a);
};
template<class T>
void sample<T> ::display(T a)
{
x=a;
cout<<"\nx="<<x;
}
void main()
{
sample<int> obj;
sample<char> obj1;
obj.display(12);
obj1.display('c');
}
Output
x=12
x=c

37

Non-Type Template Arguments


It is possible to use non-type arguments in template with multiple arguments.
Syntax
template<class T, int k>
class class_name
{
//body with type t and int k
...
}
Example Program
#include<iostream.h>
template<class T1,int b>
class test
{
T1 a;
public:
test( T1 x)
{
a=x;
}
void show()
{
cout<<"\na="<<a<<"\tb="<<b;
}
};
void main()
{
test<int,10>tobj1(3);
test<char,20>tobj2('c');
tobj1.show();
tobj2.show();
}
Output
a=3 b=10
a=c b=20

38

Вам также может понравиться