Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter4 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Chapter 4

Class and Object


Introduction:
Defining a class means creating user defined data type and it behaves like the built-in
data types of programming languages. A class serves as a blue print or a plan or a
template for an object. It specifies what data and what functions will be included in
objects of that class. Once a class has been defined, we can create any number of objects
belonging to that class. An object is an instance of a class. A class binds the data and its
associated functions together. It allows the data to be hidden, if necessary, from external
use.

Declaration of Class:
Class declaration describes the type and scope of its members. Syntax for class
declaration is like
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
an example:
class box
{
private:
float len, br, height;
public:
void get_data();
float volume();
};

Here, class is c++ keyword; class_name is name of class defined by user. The body of
class enclosed within braces and terminated by a semicolon. The class body contains the
declaration of variables and functions. These variables and functions are known as class
members (member variables and member functions). Again, keyword private and public
within class body specifies the visibility mode of variables and functions i.e. they specify
which of the members are private and which of them are public. The class members that
have been declared as private can be accessed only from within the class but public
members can be accessed from outside of the class also. Using private declaration, data
hiding is possible in C++ such that it will be safe from accidental manipulation. The use
of keyword private is optional. By default, all the members are private. Usually, the data
within a class is private and the functions are public. C++ provides a third visibility
modifier, protected, which is used in inheritance. A member declared as protected is
1
Prepared By:
Er. Dipesh Bista
accessible by the member functions within its class and any class immediately derived
from it. (The detail will be described in another chapter inheritance)
A class binds data and functions together into a single class-type variable, known as
encapsulation. The data hiding mechanism is illustrated by following figure.

Fig: data hiding in classes

Class Objects:
An Object is an instance of a class. Creating an object of a class is like defining a
variable of a data type. Once a class has been declared, we can create variables of that
type by using the class name. Syntax for creating an object is
class_name object_name;
e.g.
box b1; // here box is assumed to be a class name
The statement box b1; creates a variable b1 of type box. This variable b1 is known as
object of the class box. Thus, class variables are known as objects. The objects can also
be created when a class is defined by placing their names immediately after the closing
braces like
class box
{ private:
……..
public:
……
}b1,b2,b3;
But, this technique is rarely used in practice.

Accessing class members:


The private data or function of a class can be accessed only through the member
function of that class. The member function can access all the data and functions as usual.
The public class member can be accessed from outside the class also. The public class
variable and function is accessed using object name and dot operator.
Syntax for accessing public data member is
Object_name.data_name;

Syntax for accessing public member function is


Object_name.function_name(actual_argument_list);
2
Prepared By:
Er. Dipesh Bista
An example:
#include<iostream.h>
#include<conio.h>
class rectangle
{
private:
float len,br;
public:
void getdata(float l, float b) // defining member functions
{ len=l;
br=b; }

void calculate_area()
{ cout<<"\nThe area is "<<(len*br); }
};

void main()
{
rectangle r1, r2; // defining two objects
clrscr();
r1.getdata(10,20); //accessing member function
r2.getdata(15,10);
r1.calculate_area();
r2.calculate_area(); }

Output:
The area is 200
The area is 150

Defining a member function:


A member function can be defined mainly in two ways: They are
i) Member function inside the class body
ii) Member function outside the class body

a) Member Function Inside the class body:


In this case, a member function is defined at the time of its declaration. The function
declaration is replaced by the function definition inside the class body. This technique is
applied in the case of short functions. The function defined within a class body is treated
as inline function. This is illustrated by following example.
class box
{
private:
float len, br, height;
public:
3
Prepared By:
Er. Dipesh Bista
void get_data() //function definition
{
cout<<"Enter length, breadth, height"<<endl;
cin>>len>>br>>height;
}
float volume() //function definition
{ return(len*br*height); }
};
void main()
{
box b1;
float result;
clrscr();
b1.get_data();
result=b1.volume();
cout<<"The volume is:\t"<<result;
}

Output:
Enter length, breadth, height 12 3 4
The volume is: 144

In this example, the functions get_data() and volume() are defined within body of class
box.

b) Member Function Outside the class body:


In this technique, only declaration is done within class body. The member function that
has been declared inside a class has to be defined separately outside the class. The syntax
for defining the member function is as
return_type class_name :: function_name(argument_list)
{
//function body
}
Here, class_name:: is known as a membership identity label which tells the compiler
which class the function belongs to (i.e. function_name belongs to class_name). The
symbol :: is called scope resolution operator.

An example:
class box
{
private:
float len, br, height;
public:
void get_data();
float volume();
};
4
Prepared By:
Er. Dipesh Bista
void box::get_data() //function definition outside the class body
{
cout<<"Enter length, breadth, height"<<endl;
cin>>len>>br>>height; }

float box::volume() //function definition outside the class definition


{ return(len*br*height); }

void main()
{
box b1;
float result;
b1.get_data();
result=b1.volume();
cout<<"The volume is:\t"<<result;
}
Output:
Enter length, breadth, height 10 2 3
The volume is: 60

In this example, get_data() and volume() functions are member functions of class box.
They are declared within class body and they are defined outside the class body. While
defining member functions, box:: (membership identity label) specifies that member
functions belong to the class box. Other are similar to normal function definition.

“this” pointer:
In addition to the explicit parameters in their argument lists, every class member function
(method) receives an additional hidden parameter, the "this" pointer. The "this" pointer
addresses the object on which the method was called. Thus, this pointer is used as a
pointer to the class object instance by the member function.
Each object maintains its own set of data members, but all objects of a class
share a single set of methods. This is, a single copy of each method exists within the
machine code that is the output of compilation and linking. A natural question is then if
only a single copy of each method exists, and its used by multiple objects, how are the
proper data members accessed and updated. The compiler uses the "this" pointer to
internally reference the data members of a particular object. Suppose, we have an
Employee class that contains a salary member and a setSalary method to update it. Now,
suppose that two Employees are instantiated.
class Employee
{
public:
void setSalary(double sal)
{ salary = sal; }

5
Prepared By:
Er. Dipesh Bista
void display()
{ cout<<"\nThe salary:"<<salary; }
private:
double salary;
};

int main()
{ Employee programmer;
Employee managar;
managar.setSalary(60000.0);
programmer.setSalary(40000.0);
managar.display();
programmer.display();
}
If only one setSalary method exists within the binary that is running, how is
the correct Employee's salary updated? The compiler uses the "this" pointer to correctly
identify the object and its members. During compilation, the compiler inserts code for the
"this" pointer into the function. The setSalary method that actually runs is similar to the
following pseudo-code.

void setSalary(Employee *this, float sal)


{
this->salary = sal;
}

The correct object is identified via the "this" pointer.

Example: This example show the use of this for displaying starting address of object

class this_example
{
private:
int a;
float data;
public:
void address() // display address of the object which calls the function
{ cout<<"\nThe address of object is "<<this; }
};
void main()
{
this_example obj1, obj2;
obj1.address();
obj2.address();
}

6
Prepared By:
Er. Dipesh Bista
Output:
The address of object is 0x8fd3fff0
The address of object is 0x8fd3ffea

Example: This example shows the use this pointer


#include<iostream.h>
#include<conio.h>
class this_pointer_example
{
int data1;
public:
int getdata() //Function using this pointer for C++ Tutorial
{ return this->data1; }
void setdata(int newval) //Function without using this pointer
{ this->data1 = newval; } //same as data1=newval;
};

void main()
{
int result;
this_pointer_example obj;
obj.setdata(10);
result=obj.getdata();
cout<<"\nThe result is: "<<result;; }

Output:
The result is 10

Characteristics of this pointer:


• this pointer stores the address of the class instance, to enable pointer access of the
members to the member functions of the class.
• this pointers are not accessible for static member functions.
• this pointers are not modifiable.

Static Data Members:


A data member can be made static by using prefix static. The default value for static
data member is zero and other values can be initialized. The important property of such
variable is that only one copy of that member is created for entire class and is shared by
all the objects of the class. This type of variable is also called class variable. It is visible
within the class but its life time is the entire program.
Example:
#include<iostream.h>
#include<conio.h>
class fruit
{
private:
7
Prepared By:
Er. Dipesh Bista
static int count;
char name[15];
public:
void get_name()
{ cout<<"\nEnter name of fruit\t";
cin>>name; }

void display_name()
{ cout<<"\nThe name of apple\t"<<name; }

void count_object()
{ count++; }

void display_count()
{ cout<<"\nThe value of count i.e. no of objects "<<count; }
};

int fruit::count; //definition of static data member

void main()
{
fruit m, a;
m.get_name();
a.get_name();
m.display_name();
a.display_name();
m.count_object();
a.count_object();
m.display_count();
a.display_count();
}
Output:
Enter name of fruit mango
Enter name of fruit apple
The name of apple mango
The name of apple apple
The value of count i.e. no of objects 2
The value of count i.e. no of objects 2

The above example shows a variable count as static. This variable is shared by all objects
(here 2 objects) and counts the number of objects. The important point to be remembered
is that static member variable must be defined outside the class definition.

8
Prepared By:
Er. Dipesh Bista
Static Member Function:
Like static data member, member function can be made static by using keyword
static before function name. A static function can access to only other static data
members or static member functions. Again, static member function can be called using
the class name instead of object name. It is called as
class_name:: function_name(argument_list);

An example:
class fruit
{
private:
static int count;
char name[15];
public:
void get_name()
{ cout<<"\nEnter name of fruit\t";
cin>>name; }

void display_name()
{ cout<<"\nThe name of apple\t"<<name; }

void count_object()
{ count++; }

static void display_count()


{ cout<<"\nThe value of count i.e. no of objects "<<count; }

};
int fruit::count;

void main()
{
fruit m, a;
m.get_name();
a.get_name();
m.display_name();
a.display_name();
m.count_object();
a.count_object();
fruit::display_count(); //accessing static member function
}

Output:
Enter name of fruit banana
Enter name of fruit apple
The name of apple banana
9
Prepared By:
Er. Dipesh Bista
The name of apple apple
The value of count i.e. no of objects 2

Pointer within a class:


An example which asks for number of seven subjects and according to number of
subjects reserves memory at run time. Then, it asks for marks for each subject and finally,
calculates percentage of the student.
i.e.
class X
{ private:
float *ptr; int num;
public:
void get_numbers()
{ cout<<"Enter a number of subjects"<<endl;
cin>>num; }
void get_marks();
void calc_display();
};

void X::get_marks()
{ cout<<"Enter marks of "<< num<<" subjects"<<endl;
ptr=new float[num];
for (int i=0;i<num;i++)
cin>>*(ptr+i);
}

void X::calc_display()
{ float sum=0, per;
for(int j=0;j<num;j++)
sum=sum+*(ptr+j);
per=sum/num;
cout<<"\nThe percentage is :"<<per;
delete [] ptr; }

void main()
{ X x;
x.get_numbers();
x.get_marks();
x.calc_display(); }

Passing Object as argument:


An object can be passed into function as function argument like normal variables. This
is illustrated from following example. This example shows addition of two complex
numbers.

10
Prepared By:
Er. Dipesh Bista
#include<iostream.h>
#include<conio.h>
class complex
{
private:
int real, imj;
public:
void get_complex();
void add_complex(complex, complex);
void display_complex();
};

void complex:: get_complex()


{ cout<<"Real part:\t";
cin>>real;
cout<<"\nImj Part:\t";
cin>>imj; }

void complex::display_complex()
{ cout<<"The sum is:\t" ;
cout<<real<<"+j"<<imj; }

void complex::add_complex( complex c1, complex c2)


{ real=c1.real+c2.real;
imj=c1.imj+c2.imj; }

void main()
{
complex first, second, result;
clrscr();
cout<<"\nEnter first complex number\n";
first.get_complex();
cout<<"\nEnter second complex number\n";
second.get_complex();
result.add_complex(first,second); //objects first and second passed as argument
result.display_complex();
getch();
}

Output:
Enter first complex number
Real part: 2
Imj Part: 4
Enter second complex number
Real part: 1
Imj Part: 8
11
Prepared By:
Er. Dipesh Bista
The sum is: 3+j12

Returning Objects from Function:


An function can return object to the calling function as it can return integer, float….
values. This can be explained as following example.
An Example:
#include<iostream.h>
class distance
{
private:
int feet;
float inches;
public:
void get_distance();
distance add_distance(distance, distance);
void display_distance();
};

void distance:: get_distance()


{ cout<<"Enter Feet:\t";
cin>>feet;
cout<<"\nEnter Inches:\t";
cin>>inches; }

void distance::display_distance()
{ cout<<"The sum is:\t" ;
cout<<feet<<"\'-"<<inches<<'\"'; }

distance distance::add_distance( distance d1, distance d2)


{
distance sum;
sum.inches=d1.inches+d2.inches;
if(sum.inches>=12)
{
sum.inches-=12;
sum.feet=1;
}
sum.feet+=(d1.feet+d2.feet);
return (sum); //object return
}

void main()
{
distance first, second, result;
cout<<"\nEnter first distance\n";
first.get_distance();
12
Prepared By:
Er. Dipesh Bista
cout<<"\nEnter second distance\n";
second.get_distance();
result=result.add_distance(first,second);
result.display_distance();
}

Output:
Enter first distance
Enter Feet: 3
Enter Inches: 9
Enter second distance
Enter Feet: 5
Enter Inches: 5
The sum is: 9'-2"

In this example, function add_distance() passes two objects as arguments and it returns
value of type distance i.e. object of class distance. The returned object is stored in another
object result in main() function.

Friend Functions and Friend Classes:


A function is made to be friend of a class by using keyword friend before function
declaration within class body. The friend function can access private data of the class for
which it is declared as friend, although it is not member function of the class. The
function definition doesn’t use either keyword friend or the scope resolution operator. A
function can be declared as friend in any number of classes.

Characteristics of Friend Function:


¾ Although friend function is not member function, it has full access to the private
data of the class.
¾ Friend Function is called like a normal function without the help of any object.
¾ While using member data or functions, it uses object name and dot membership
operator with each member name
¾ Usually, it has objects as arguments.
¾ Member function of one class can be friend function of another class. In such
case, the member function is defined using the scope resolution operator. As
class X {………….
int function1();
};
class Y{…….
friend int X:: function1();
};

Example for friend function:

class friendTest
{
13
Prepared By:
Er. Dipesh Bista
float first,second;
public:
void get_value()
{ cout<<"Enter two numbers"<<endl;
cin>>first>>second; }
friend float calculate_mean(friendTest s);
};

float calculate_mean(friendTest s)
{ return((s.first+s.second)/2.0); }

void main()
{
friendTest x;
x.get_value();
cout<<"Mean of these two numbers is "<<calculate_mean(x);
}

A class can be declared as friend class of other such that all the member functions of one
class are friend functions of later class. An example:
class X
{
float first,second;
public:
void get_value()
{ cout<<"Enter two numbers"<<endl;
cin>>first>>second; }
friend class Y;
};

class Y
{ public:
void display_data(X obj)
{cout<<"\nThe first number is: "<<obj.first<<"\nThe second number is:
<<obj.second; }
};

void main()
{ X x;
Y y;
x.get_value();
y.display_data(x); }

14
Prepared By:
Er. Dipesh Bista

You might also like