Cppmod 2
Cppmod 2
OBJECT
UNIT STRUCTURE
8.2 INTRODUCTION
So far, we have learnt that C ++ lets you create variables which can be of
a range of basic data types : int, long, double and so on. However, the
variables of the basic type do not allow you to model realworld objects (or
even imaginary objects) adequately. We come to know that the basic theme
of the object oriented approach is to model the real –world problems. So,
object oriented programming language C++ introduces a new data type
called class by which you can define your own data types as class. Defining
the variables of a class data type is known as a class instantiation and
such variables are called objects. In this unit, we will introduce you how to
declare a class and how to create objects of a class.We will also discuss
how a member function declare inside a class or outside a class and how
it can be accessed. Moreover, the techniques of passing objects as function
arguments are also illustrated in this unit.
For example, the objects ‘computer’ & ‘car’ have the following attributes
and operations–
Object : car
Attributes: company, model, colour, & capacity
Object: Computer
Attributes: brand, price, monitor resolution, hard disk and RAM size
Each object will have its own identity though its attributes and operation
are same, the objects will never become equal. In case of person object,
for instance, two person have the same attributes like name, age and sex,
but they are not equal. Objects are the basic run time entities in an object
– oriented system. Thus, in C++, an object is a collection of related
variables and function bound together to form a high level entity. Thus,
Class
Data
data 1
data 2
data 3
Functions
Func 1 ( )
Func 2 ( )
Func 3 ( )
Thus, the entire group of data and code of an object can be built as a
user-define data type using class. It is obvious that classes are the basic
language construct in C++ for creating the user defined data types. Once
a class has been declared, the programmer can create a number of objects
associated with that class. Objects are nothing but the variable of the class
data type. Defining variables of a class data type is known as a class
instantiation. The syntax used to create an object of the class data type
is similar to the syntax used to create an integer variable in C. In the next
section, we will learn how to declare a class and an object.
We have come to know that classes contain not only data but also
functions. Data and functions within a class are called members of a class.
The data inside a class is called a data member and the functions are
called member function. The member functions define the set of
operations that can be performed on the data member of a class. The
syntax of a class declaration is shown below—
The keyword ‘class’ indicates the name which follows class name, is an
abstract data type. The declaration of a class is enclosed with curly braces
and terminated by a semi-colon. The body of a class contains declaration
of data members and member functions.
The members of a class are usually grouped in two sections i.e. private
and public, which define the visibility of members.
insert_data ( )
float age
private: name [30]
insert_data ( ) age
show_data ( )
show_data ( )
symbol. All the members that follow a keyword (upto another keyword)
belong to that type. If no keyword is specified, then the members are
assumed as private member. We will discuss later about the
protected keyword. Let us now briefly discuss about private and public
keywords.
A class declaration only builds the structure of objects. In our example, the
class employee does not define any objects of employee but only specifies
what it will contain. Once a class has been declared, we can create variable
of that type by using the class name (like any other built-in type variable).
The process of creating objects (variables) of the class is called class
instantiation. For example–
int x, y, z; // declaration of integer variables
float m, n; // declaration of float variables
employee a; // declaration of object or class variable
In a single statement we can create more than one object as shown below.
This practice is rarely followed because we would like to define the objects
as and when required, or at the point of their use.
Both e1 and e2 have the same data members and it is illustrated by the
following figure.
e1 e2
Here, in the figure the objects e1 and e2 occupy the memory area. They
are not initialized to anything; however the data members of each object
will simply contain junk values. So, our main task is to access the data
members of the object and setting them to some specific values.
An object is a conceptual entity having the following properties:
- it is individual
- it points to a thing, either physical or logical that is identifiable by the
user.
- it holds data as well as operation method that handles data.
- its scope is limited to the block in which it is defined.
dot operator
The following program demonstrates how the objects are used for
accessing the class data members.
//Program 8.1
# include <iostream.h>
# include <string.h>
# include <conio.h>
class employee
{
private:
char name [30]; // name of an employee
float age; // age of an employee
public : // initializing data members
void insert_data (char * name1, float age)
{ strcpy (name, name1);
age = age1;
}
void show_data ( ) //displaying the data members
{
cout << “Name :”<<name<<endl;
cout << “Age :”<<age<<endl;
}
};
void main ( )
{
employee e1; //first object of class employee
employee e2; //second object of class employee
clrscr( );
e1.insert_data(”Hemanga”,30);
//e1 calls member insert_data ( )
e2.insert_data (”Prakash”,32);
//e2 calls member insert_data ( )
cout << “Employee Details:”<<endl;
e1.show_data ( ); // e2 calls member show_data (
)
e2.show_data ( ); // e2 calls member show_data (
)
getch ( );
}
In the above program, in main( ) we have declared two objects through the
statements
employee e1; and employee e2;
The statements
e1.insert_data (“Hemanga”, 30);
e2.insert_data (“Prakash”, 32);
initialize the data members of object e1 and e2. The object e1’s data
member ‘name’ is assigned ‘Hemanga’ and age is assigned 30. Similarly,
the object e2’s data member ‘name’ is assigned ‘Prakash’ and age is
assigned 32.
The statements
e1.show_data ( );
e2.show_data ( );
We have already come to know that a class holds both the data and
functions which are called data members and member functions. The
data member of a class must be declared within the body of the class.
The member functions of a class can be defined in two places
inside the class definition
outside the class definition
It is obvious that a function should perform the same task, no matter where
it is defined. But the syntax of a member function definition changes
depending on the place of its definition, i.e. inside a class or outside a
class. We will now discuss both the approaches.
In this method, the function is defined inside the class body. When a
function is defined inside a class, it is treated as an inline function.
We will discuss inline function in the next section.
In the program 8.1 we have defined the member functions–
and
void show_data ( );
The function defined outside the body of a class have the same syntax
as normal functions i.e. they should have a function header and a
function body. But, there must have a mechanism of binding the
functions to the class to which they belong. This is done by using the
scope resolution operation (: :), in the header of the function. The
scope resolution operator acts as an ‘identity-label’ and tells the
compiler the class to which the function belongs. The general form
of a member function definition is shown below–
ClassName
{ ............
............
Here, the label ClassName : : tells the compiler that the function
MemberFunction is the member of class ClassName. The scope
of the function is restricted to only the objects and other members of
the class. We can modify the Program 8.1 by defining the member
functions outside the class body, as shown below:
//Program 8.2
#include<iostream.h>
#include<string.h>
#include<conio.h>
class employee
{
private:
Char name [30];
float age;
public:
void insert_data (char *name1, float age1);
void show_data ( );// Member Function
};
void employee::insert_data (char *name1, float age1)
{
strcpy (name, name1);
age = age1;
}
void employee ::show_data ( )// Function definition
{
cout <<“Name :”<<name<<endl;
cout <<“Age:”<<age<<endl;
}
void main ( )
{
employee e1, e2;
clrscr( );
e1 . insert_data (“Hemanga”, 30);
e2 . insert_data (“Prakash”, 32);
cout<<“EMPLOYEE DETAILS....”<<endl;
e1 . show_data ( );
e2 . show_data ( );
getch ( );
}
A program can have several different classes and they can use
the same name for different member functions. The ‘membership
label’ (ClassName : :) resolves the ambiguity of the compiler in
deciding which function belong’ to which class.
Let us first see what an inline function is. C++ provides a mechanism
called inline function. When a function is declared as inline, function body
is inserted in place of function call during compilation. In this mechanism,
passing of control between caller and callee functions is avoided. The use
of the inline function is most effective when calling function is small. If the
calling function is very large, in such a case also, compiler copies the
content of the inline function in the called function which reduces the
program’s execution speed. So, in such a case inline function should not
be used.
Now, let us see how an inline function behaves with class specification.
We have come to know that we can define a member function outside the
class definition. The same member function can be defined as inline
function by just using the qualifier inline in the header line of the function
defining. In the followng, the syntax for defining inline function outside the
class declaration is shown
// Program 8.3
#include<iostream.h>
#include<string.h>
#include<conio.h>
class employee
{
private:
char name [30];
float age;
public :
void insert_data (char *name1, float age1);
void show_data ( );
} ;
void main()
{
employee e1, e2;
clrscr( );
e1.insert_data (“Hemanga”, 30);
e2.insert_data (“Prakash”, 32);
cout<< “Employee Details ..” << endl;
e1.show_data ( );
e2.show _data ( );
getch ( );
}
OUTPUT :
Employee Details–
Name : Hemanga
Age : 30
Name : Prakash
Age : 32
We know that arrays hold data of similar type. Arrays can be of any data
type including user defined data type, created by using struct, class etc.
We can create an array of variables by using class data type. Such an
Here, the identifier ‘employee’ is a user defined data type and can be used
to create objects that relate to different categories of employees. For
example, the following definition will creates an array of objects of ‘employee’
class–
employee consultant [30]; // array of cosultant
employee clerk [15]; // array of clerk
name
consultant [0]
age
name
consultant [1]
age
name
consultant [2]
age
name
consultant [29]
age
consultant [ 30 ] . show_data ( )
We can rewrite the Program 8.1 by using array of objects as shown below:
// Program 8.4
#include<iostream.h>
#include<string.h>
#include<conio.h>
class employee
{
private:
char name [30];
float age;
public:
void insert_data (char *name1, float age)
{
strcpy (name, name1);
age = age1;
}
void show_data ( )
{
cout<<“Name:”<<name<<endl;
cout<<“Age:”<<age<<endl;
}
};
void main ( )
{
int i, age, count;
char name [30], tag;
employee consultant [30];
clrscr ( );
count = 0;
for (i=0; i<30; i++)
{
cout<<“Enter Data For Employee (Y/N):”;
cin >> tag;
if (tag = = ‘y’ || tag = = ‘Y’)
{
cout <<“\n Enter Name of Employee:”;
cin >> name;
cout << “Age:”;
cin >> age;
consultant[i].insert_data(name, age);
count ++;
}
else
break;
}
cout <<“\n\n Employee Details ......\n” ;
Employee Details...
Name : Prakash
Age : 30
Name : Hemanga
Age : 28
only the address of the object is sent implicitly to the function, which
is also called – pass by-reference.
8.9.1 Pass-by-value
//Program 8.5
#include<iostream.h>
#include<conio.h>
class age
{
private:
int birthyr ;
int presentyr ;
int year ;
public:
void getdata ( );
void period (age);
};
}
OUTPUT: Year of Birth : 1990
Current Year : 2002
Your Present Age : 19 years
In the above program, the class age has three data member. The function
getdata ( ) reads integers through keyboard. The function period ( )
calculates the difference between the two integers. In function main ( ), a1
is an object to the class age. The object a1 calls the function getdata ( ).
The same object a1 is passed to the function period ( ), which calculates
the difference between the two integers. Thus, an object can be passed to
a function.
8.9.2 Pass-by-Reference
In this technique, only the address of the object is sent to the function.
When an address of the object is passed, the address acts as reference
pointer to the actual object in the calling funciton. Therefore, any change
made to the objects inside the called function will reflect in the actual object
in the calling funciton. We can modify the program 8.5 by using the pass
by reference mechanism
// Program 8.6
#include<iostream.h>
#include<conio.h>
class age
{
private:
int birthyr ;
int presentyr ;
int year ;
public:
void getdata ( );
void period (age);
};
{
x1. year = x1 . presentyr - x1 . birthyr ;
cout << “Your Present Age :” <<year<<“Years” ;
}
void main ( )
{
clrscr ( );
age a1 ;
a1 . getdata ( );
a1 . period (a1) ;
getch ( );
}
8.9.3 Pass-by-Pointer
//Program 8.7
#include<iostream.h>
#include<conio.h>
class age
{
private:
int birthyr ;
int presentyr ;
int year ;
public:
void getdata ( );
void period (age * );
};
In Program 8.6 and Program 8.7 we need to keep an eye on the symbols
‘.’, ‘ ’, ‘*’, ‘&’, and the statements(bold lines) where we have appropriately
used them.
We have already discussed the fact that the private members of a class
cannot be accessible from the outside of the class. Only the member
functions of that class have permission for accessing the private members.
This policy enforces the encaptulation and data hiding techniques.
class test
{
private:
---------
---------
public :
---------
---------
friend void sum( ) ;
};
The function can be defined anywhere in the program similar to any normal
C++ function. The function definition does not use either the keyword friend
or the scope operator ‘: :’. The functions that are declared with the keyword
‘friend’ are called friend functions. A friend function can be a friend to a
multiple classes. The friend function have the following properties :
There is no scope restriction for the friend function; hence they can
be called directly without using objects.
// Program 8.8
#include<iostream.h>
#include<conio.h>
class first ; /*forward declaration like function Prototype*/
class second
{
int x ;
public :
void get value ( )
{
cout << “\n Enter a number :” ;
cin >> x ;
}
friend void sum(second, first); //declaration of friend
dunction
} ;
class first
{
Object Oriented Programming through C + + (Block - 2) 31
Unit - 8 Introduction to Classes and Object
int y ;
public :
void getvalue ( )
{
cout << “\n Enter a number:” ;
cin >> y ;
}
friend void sum (second, first) ;
} ;
void sum (second m, first n)
{
cout << “\n Sum of two numbers :” << n.y + m.x
}
void main( )
{
clrscr ( );
first a ;
second b ;
a.get value ( ) ;
b.get value ( ) ;
sum(b,a);//funciton is called like a general function in C++
}
In the above program each of the two classes ‘first’ and ‘second’ has a
member function named getvalue ( ) and one private data member. Notice
that, the function sum ( ) is declared as friend function in both the class.
Hence, this function has the ability to access the members of both the
classes. Using sum ( ) function, addition of integers is calculated and
displayed.
It is possible to declare all the member functions of a class as the friend
functions of another class. When all the functions need to access another
class in such a situation we can declare an entire class as friend class.
Always remember that friendship is not exchangeable. Its meaning is that
32 Object Oriented Programming through C + + (Block - 2)
Introduction to Classes and Object Unit - 8
class second
{
-------
-------
friend class first;
}; /* all member functions of class first are friends to
class second */
//Program 8.9
#include<iostream.h>
#include<conio.h>
class smallvalue;
class value
{
int a;
int b;
public:
value (int i, int j) // declaration of constructor with
arguments
{
a = i;
b = j;
}
};
void main ( )
{
value x (15, 25);
clrscr ( ) ;
smallvalue y;
cout << y. minimum(x);
getch ( );
}
In the above program we have used the constructor with arguments. The
concept of constructor is illustrated in unit 9 ‘Constructors and
Destructors’.
After studying public and private members, let us study about the static
members of a class. Recall what we have learnt from C Programming:
(i) A variable can be declared as static inside a function or outside
main().
(ii) Static variables value do not disappear when function is no longer
active; their last updated value always persists. That is, when the
control comes back to the same function again the static variables
have the same value as they leave at the last time.
in C++ also. However, C++ has objects. Hence, the meaning of static with
respect to member variables of an object is different.
We have already gained the idea that each object has its separate set of
data member variable in memory. The member functions are created only
once and all object share the function. No separate copy of the function of
each object is created in the memory like data member variables. Figure
8.5 shows the accessing of member function by objects.
Object A Object B
Variable 1 Variable 1
Variable 2 Variable 2
Variable n Variable n
fun A ( )
fun B ( )
fun C ( )
Object C Object D
Variable 1 Variable 1
Variable 2 Variable 2
Variable n Variable n
Fig. 8.5 Data members and member functions in memory
Object Oriented Programming through C + + (Block - 2) 35
Unit - 8 Introduction to Classes and Object
The syntax for declaring static data member or member function within a
class is shown below:
static <variable name> ;
static <function name> ;
When you declare a static data member within a class, you are not defining
it i.e. you are not allocating storage for it. Instead, you must provide a
global definition for it elsewhere, outside the class. This is done by
redeclaring the static variable using the scope resolution operator to identify
the class to which it belongs. This causes storage for the variable to be
allocated.
Object A Object B
Variable 1 Variable 1
Variable 2 Variable 2
Variable n Variable n
Static variable
Object C Object D
Variable 1 Variable 1
Variable 2 Variable 2
Variable n Variable n
// Program 8.10
#include<stdio.h>
#include<conio.h>
class number
{
static int C;
public:
void count ( )
{
C ++;
cout << “\n C =” << C;
}
};
int number : : C = 0;
void main( )
{
number a, b, c;
clrscr ( ) ;
a.count ( );
b.count ( );
c.count ( );
getch ( );
}
Object Oriented Programming through C + + (Block - 2) 37
Unit - 8 Introduction to Classes and Object
OUTPUT: c = 1
c=2
c=3
In the above program, the class number has one static data variable C.
The count( ) is a member funciton, increment value of static member
variable C by 1 when called. The statement int number : : C = 0 initiatize
the static member with 0. It is possible to initialize the static data members
with other values. In the function main( ), a, b and c are three objects of
class number. Each object calls the funciton count( ). At each call to the
function count( ) the variable C gets incremented and the count statement
displays the value of variable C. The objects a, b and c share the same
copy of static data member C.
a) Just one copy of the static member is created in the memory for the
entire class. All objects of the class share the same copy of static
member.
e) When one of the objects changes the value of data member variables,
the effect is visible to all the objects of the class.
The following program demonstrates the use of the static member function
in a class.
//Program 8.11
#include<iostream.h>
#include<conio.h>
class number
{
private:
static int X;
public:
static void count ( ) {X++; }
static void display ( )
{
cout << “\n value of X =” << X;
}
};
int number : : X = 0;
void main ( )
{
clrscr ( ) ;
number::display( ); //invokes display function
number::count( ); //invokes count function
number::count( ); //invokes display function
number::display( ); //invokes display function
getch ( );
}
OUTPUT: Value of X : 0
Value of X : 2
In the above program, the member variable X and functions count ( ) &
display ( ) of class number are static. The function count ( ) when called,
increases the value of static variable X. The function display ( ) prints the
current value of the variable X. The static functions can be called using
class name and scope resolution operator as shown in the program–
number : : count ( );
number : : display ( );
Object Oriented Programming through C + + (Block - 2) 39
Unit - 8 Introduction to Classes and Object
Classes are the basic language construct in C++ for creating the
user defined data types.
A class contains member variable or data members and member
functions.
The members of a class are grouped into two sections, namely,
private and public.
Defining variables of a class data type is known as a class instantiation
and such variables are called objects.
Using the member accessed operator, dot(.), the class members
can be access by the objects.
The member function can be defined as a) private or public b) inside
the class or outside the class.
The scope resolution operator (::) is used, when a member function
is defined outside the class body.
Inline member function is treated like a macro, when a function is
declared as inline, function body is inserted in place of function call
during compilation.
We can create an array of variables by using the class data type,
then these variables are called array of objects, which occupies
contiguous memory locations inmemory.
There are three methods of passing objects to function, namely,
pass-by-value, pass-by-reference, and pass-by-pointer.
The function that are declared with the keyword friend are called
friend function. A function can be a friend to multiple classes.
static is the keyword used to preserve value of a variable. When a
variable is declared as static, it is initialized to zero. A static function
or data element is only recognized inside the scope of the present
class.
When a function is defined as static, it can access only static member
variables and functions of the same class. The static member
functions are called using its class name without using its objects.
1. a) i. b) iii. c) iv. d) i. e) ii
2. i) inline, ii) pass-by-pointer, iii) friend
3. a) False, b) True, c) False
**********