Академический Документы
Профессиональный Документы
Культура Документы
Objects
Classes
Data Abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
Object
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;
};
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
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.
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.
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
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;
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
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
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
//function declaration-default
Output
k=19.8
k=20
5
const arguments
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
..
..
}
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
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.
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.
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
// function declaration
// function definition inside the class
OUTPUT
i=10
k=19
9
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;
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
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
Types of Constructor:
Default Constructor
Parameterized Constructor
Multiple Constructor
Constructor with Default Arguments
Copy Constructor
Dynamic Constructor
Default Constructor
Syntax
classname()
{
//Constructor Definition
12
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:
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
Copy Constructor
Copy constructor is used to declare and initialize an object from another object.
For example
integer i2(i1);
integer i2=i1;
A copy constructor will takes reference to an object of the same class as itself as an argument.
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(){}
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
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.
Assignment operator =
Function call operator ()
Subscripting operator []
Class member access operator
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
#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
Unary operator when overloaded by means of a friend function takes one reference argument.
Output:
x=10
y=20
z=-21
after activating operator () function
x=-10
y=-20
z=21
21
Binary operators overloaded by member function takes one explicit argument and those
overloaded through friend takes two explicit arguments.
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
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.
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
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.
In the above program the operator function converts an integer to double value.
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{};
void main()
{
b objb;
objb.displaya();
objb.displayb();
}
Output
base class
derived class
Multiple Inheritance
Syntax
class A{}
C
class B{..}
class C:public A,public B{.};
class C is derived from two base classes A and B.
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{...};
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{...};
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
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=3.2 a=w
33
b=5.4
b=t
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.
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
}
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
38