You are on page 1of 14

Objects and Classes

Introduction:
The main purpose of developing C++ programming was to implement
object-oriented programming concepts in C programming language.
In Object Oriented Programming everything in the real world is considered
either attributes or methods. Attribute is something an object has and operations
or methods is something the attribute does. [LegsWalking]
For example: If you consider a bank account as an object in Real world. It
will have account number, account type, balance that can be considered as
attribute. Whereas the operations of withdrawing money and depositing money
can be considered as methods.
The object-oriented programming approach normally Associates attribute
with variable and operations(methods) with functions.
A class is a user-defined data type that groups functions and variables
associated with an object together. It can then be used as an object constructor,
or a "blueprint" for creating objects.
The initial name of C++ was ‘C with classes’, thus we can say that a class is
the single most important feature of C++ programming.
The basic idea of a class was developed by modifying the concept of
structure in C language and adding OOPS concepts to it.
4.1 Specifying a class:
A class is a way to bind the data and its associated functions together. It
allows the data (and functions) to be hidden, if necessary, from external use.
When defining a class, we are creating a new abstract data type that can be
treated like any other build-in data type.
Generally, a class specification has two parts:
1. Class declaration
It describes the type scope of its members.
2. Class function definitions
It describes how the class functions are implemented.
The general form of a class is:
class class_name Class Name

{  Opening Brace

private:
variable declaration;
function declaration;
public: Class Body
variable declaration;
function declaration;
};  Closing Brace and terminating semicolon

When you define a class, you define a blueprint for a data type.
A class definition starts with the keyword class followed by the class name
and the class body enclosed by a pair of curly braces, followed by a semicolon.
The class body contains declaration of variables and function.
The variables and functions in a class are together known as class members.
The Variables inside the class are known as Data members.

31
The function inside the class are known as Member function.
Objects and Classes
4.2 Private and Public:
To handle your data in a systematic manner object-oriented programing
offers a feature known as Data hiding.
The concept of Data-hiding is implemented in C++ using Access modifiers.
That is C++ offers the possibility to control access to class Data members
and Member function by using Access Modifiers (also known as Access Specifiers).
Access Modifiers
Access Modifiers are keywords that are used to set the accessibility of Data
members and Member function of a class. In simple terms we can say that they
set some rules on who can access the data and who can’t.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected (Not in Syllabus)
1- Public:
As the name suggests, available to all. All the members of the class will be
available to everyone after declaring them as public.
A public member can be accessed anywhere outside the class but within a
program. Data members can be also accessed by other classes if declared public.
As there are no restrictions in public modifier, we can use the (.)dot
operator to directly access member functions and data.
2- Private:
The class members declared as private can be accessed only by the
functions inside the class. They are not allowed to be accessed directly by any
object or function outside the class.
Only the member functions or the friend functions are allowed to access
the private data members of a class.
You will get a compile-time error while trying to access private data
members from anywhere outside the class.
By default, all the members of a class would be private.
Where/When to use Public and Private member function?
It is the normal practice to place all
the data items in private section in all the
functions in public section of a class.
But some situation may require
certain functions to be hidden like Private
data from the outside call.
Deleting an account in a customer
file and providing in increment to an
employee are events of serious matters and
therefore the function heading service task
must have restricted access so this function must be place in the private section.
Private member function can only be called by another function that is a
member of a class in one and object cannot in a private function using the dot (.)

32
operator.
Objects and Classes
Difference between Public and Private in C++
Public Access Modifier Private Access Modifier
Example: Example:
#include <iostream.h> #include <iostream.h>
// class definition // class definition
class Circle class Circle
{ {
public: private: // private data member
double radius; double radius;

double compute_area() public: // public member function


{ void compute_area(double r)
return 3.14 * radius * radius; {
} radius = r;
//member function can access private data member radius
};
double area = 3.14 * radius * radius;
cout << "Radius is: " << radius
int main() // main function
<< endl;
{
cout << "Area is: " << area;
Circle obj; }
};
obj.radius = 5.5;
// accessing public data member outside class
int main() // main function
{
cout << "Radius is: " << obj.radius
Circle obj;
<< "\n"; // creating object of the class
obj.compute_area(1.5);
cout << "Area is: "
// trying to access private data member directly
<< obj.compute_area();
outside the class
return 0; return 0;
} }
Output: Output:
Radius is: 5.5 Radius is: 1.5
Area is: 94.985 Area is: 7.065

All the class members declared under public The class members declared as private can
will be available to everyone. be accessed only by the functions inside the
class.
The data members and member functions Only the member functions or the friend
declared public can be accessed by other functions are allowed to access the private
classes too. data members of a class.
The public members of a class can be They are not allowed to be accessed directly
accessed from anywhere in the program by any object or function outside the class.
using the direct member access operator (.)
with the object of that class.

33
Objects and Classes
4.3 Defining member functions:
A member function of a class is a function that has its definition or its
prototype within the class definition.
It operates on any object of the class of which it is a member, and has
access to all the members of a class for that object.
There are two ways in which the member functions can be defined:
1. Inside the class definition
2. Outside the class definition
If the member function is defined inside the class definition it can be
defined directly, but if its defined outside the class, then we have to use the scope
resolution :: operator along with class name along with function name.
1- Inside the class definition
As the name suggests, here the functions are defined inside the class.
If we define the function inside class then we don't not need to declare it
first, we can directly define the function.
Functions defined inside the class are treated as inline functions
automatically if the function definition doesn’t contain looping statements or
complex multiple line operations.
Example:
class Cube
{
public:
int side;
int getVolume() //Function definition is in the class it self
{
return side*side*side; //returns volume of cube
}
};

2- Outside the class definition


As the name suggests, here the functions are defined outside the class
however the functions are declared inside the class.
Functions should be declared inside the class to bound it to the class and
indicate it as it’s member but they can be defined outside of the class.
To define a function outside of a class, scope resolution operator :: is used.
Example:
class Cube
{
public:
int side;
int getVolume(); //function declaration inside the class
};
int Cube :: getVolume() // member function defined outside the class
{
return side*side*side;
}
34
Objects and Classes
4.4 Nesting of member function:
A member function of a class can be called only by an object of that class
using a dot operator. However, there is an exception to this.
A member function can call another member function of the same class
directly without using the dot operator. This is called as nesting of member
functions.

/* 09 Program to find largest among Two Numbers using Nesting


of member function in C++ */
#include<iostream.h>
#include<conio.h>
class largest
{
int m,n; //  By default everything is private in a class
public:
void input(void);
void display(void);
int large(void);
};
int largest:: large (void)
{
if(m >= n)
return(m);
else
return(n);
}
void largest:: input(void)
{
cout << "Input value of m and n"<<"\n";
cin >> m>>n;
}
void largest:: display(void) // member function calling another member function
{
cout << "largest value=" << large () <<"\n";
}
int main()
{
clrscr();
largest A;
A.input();
A.display();
getch();
return 0;
}
Output:

35
Objects and Classes
4.5 Object as data types:
Once a class is defined, it can be used to create variables of its type known
as objects. The relation between an object and a class is the same as that of a
variable and its data type.
The syntax for declaring an object is
class_name object_list;
where,
class_name is the name of the class
object_list is a comma-separated list of objects
Example:
//Declaring objects of a class
class book
{
// body of the class
} ;
int main ()
{
book bookl, book2, book3; //objects of class book
return 0;
}
In the above example, three objects namely, book1, book2 and book3 of the
class book have been created in main ().
The syntax for the declaration of objects of a particular class is same as
that for the declaration of variables of a built-in data type.
int a,b,c; // declaration of variables
book bookl, book2, book3; // declaration of objects

4.6 Memory allocation for objects


There is a difference in how memory space is allocated in C++ for data
members (Variables) and member functions. This different regardless of the fact
that both data members and member functions belong to the same class.
Once you define class it will not allocate memory space for the data member
of the class. The memory allocation for the data member of the class is performed
separately each time when an object of the class is created.
A single data member can have different
values for different objects at the same time,
every object declared for the class has an
individual copy of all the data members.
On the other hand, the memory space
for the member functions is allocated only
once when the class is defined.
In other words, there is only a single
copy of each member function, which is
shared among all the objects.

36
Objects and Classes
4.7 Static data members.
When we declare a normal variable (data member) in a class, different
copies of those data members create for different objects of that class.
But Sometimes we may need some common information that should be
same for all objects of a class. We cannot do this using normal data members.
This can be accomplished using the concept of static data member.
A type of data member that is shared among all objects of class is
known as static data member.
A static data member is defined in the class with the static keyword.
The properties of a static variables in ‘C++’ are similar to the ‘C’ static
variable.
Static variables are normally used to maintain a value that is common for
the entire program.
Properties of Static variable:
1. It is initialized to 0 when the first object of its class is created no other
initialization is permitted
2. Only one copy of that member is created for the entire glass and shared by
all the objects of that class, no matter how many classes are created
3. It is visible only within the class but its lifetime is entire program
Static data member is declared in the class but it must be defined outside the
class using class name and scope resolution operator (::) because memory
allocation for static data member of the class is performed different than normal
data member of the class and it is not the part of class object.
/* 10 Program to demonstrate Static Variable in C++ */
#include<iostream.h>
#include<conio.h>
class item
{
static int count; //Static Variable, default initialization to Zero
public:
void Counter()
{
count++;
cout<<"count = "<<count<<endl;
}
};
int item::count; // must be defined outside the class
int main()
{
item a,b,c;
a.Counter ();
b.Counter ();
c.Counter ();
getch()
return 0;
} Output :

37
Objects and Classes
4.8 Static member functions
Just like a data member we can make a member function of a class static.
By declaring a function member as static, you make it independent of any
particular object of the class.
A static member function can be called even if no objects of the class exist
and the static functions are accessed using only the class name and the scope
resolution operator (::)
A static member function can only access static data member, other static
member functions and any other functions from outside the class.
Static member functions have a class scope and they do not have access to
the ‘this pointer’ of the class.

Properties of static member functions:


A static function can only access other static variables or functions present
in the same class
Static member functions are called using the class name.

Syntax- class_name::function_name( )

Example:
class Test
{
public:
static void sf()
{
Cout << "Testing Static function!"
}
};

int main()
{
Test::sf(); // calling member function directly with class name
}

38
Objects and Classes
4.9 Array of objects
An array is a collection of data that holds fixed number of values of same
data type.
Instead of declaring individual variables, such as rollno_1, rollno_2,
rollno_3, ………… rollno_100. We can create a single array say roll_no with 100
elements in it.
Array Index: Elements in an array are stored and retrieved using array
index. The index of array starts at 0 and ends at size-1. Suppose we are storing
100 roll numbers using an array, the index range will be 0-99.
Like array of other user-defined data types, an array of type class can also
be created. Such an array is called as array of objects.
An array of objects is declared in the same way as an array of any built-in
data type.
Syntax for declaring an array of objects is
class_name array_name [size];
Example:
class books
{
char tit1e [30];
float price;
public:
void getdata ();
void putdata ();
} ;
int main ()
{
books book[3]; //books  class name ; book  name of array we created
}
In this example, an array book of the type class books and size three is
declared. This implies that book is an array of three objects of the class books.
Note: Every object in the array book can access public members of the class
in the same way as any other object, that is, by using the dot operator. For
example, the statement book [i].getdata() invokes the getdata() function for
the ith element of array book.
When an array of objects is
declared, the memory is allocated in the
same way as to multidimensional
arrays. For example, for the array book,
a separate copy of title and price is
created for each member book[0],
book[l] and book[2].
However, member functions are
stored at a different place in memory
and shared among all the array
members.

39
Objects and Classes
/* 11 Program to demonstrate Array of objects in C++ */
#include <iostream.h>
#include <conio.h>
class Student
{ string name;
int marks;
public:
void getName()
{
cin>>name;
}
void getMarks()
{
cin >> marks;
}
void displayInfo()
{
cout << "Name : " << name << "\t";
cout << "Marks : " << marks << endl;
}
};
int main()
{
clrscr();
Student st[3];
for( int i=0; i<3; i++ )
{
cout << "Student " << i + 1 << endl;
cout << "Enter name" << "\t";
st[i].getName();
cout << "Enter marks" << "\t";
st[i].getMarks();
}
for( int i=0; i<3; i++ )
{
cout << "Student " << i + 1 << "\t";
st[i].displayInfo();
}
getch()
return 0;
}
Output:

40
Objects and Classes
4.10 Objects as function argument
The objects of a
class can be passed as
arguments to member
functions as well as
nonmember functions,
this can be done in two
ways
1. By Value: Copy of
the entire object is based
to the function.
2. By Reference:
Only the address of the
object transferred to the
function.

By Value:
When an object is passed by vadlue, a copy of the actual object is created
inside the function. This copy is destroyed when the function terminates.
Moreover, any changes made to the copy of the object inside the function are not
reflected in the actual object.

By Reference:
On the other hand, in pass by reference, only a reference to that object (not
the entire object) is passed to the function. Thus, the changes made to the object
within the function are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same
class, its data members can be accessed inside the function using the object name
and the dot operator.
However, the data members of the calling object can be directly accessed
inside the function without using the object name and the dot operator.

4.11 Returning objects


In C++ programming, object can be returned from a function in a similar
way as structures.

41
Objects and Classes
Example:
/* In this example we have two functions, the function input() returns the Student
object and disp() takes Student object as an argument. */

#include <iostream.h>
#include <conio.h>

class Student
{
public:
int stuId;
int stuAge;
string stuName;
// In this function we are returning the Student object.
Student input(int n, int a, string s)
{
Student obj;
obj.stuId = n;
obj.stuAge = a;
obj.stuName = s;
return obj;
}
// In this function we are passing object as an argument.
void disp(Student obj)
{
cout<<"Name: "<<obj.stuName<<endl;
cout<<"Id: "<<obj.stuId<<endl;
cout<<"Age: "<<obj.stuAge<<endl;
}
};

int main()
{
clrscr();
Student s;
s = s.input(01, 17, "xyz");
s.disp(s);
getch()
return 0;
}

Output:

42
Objects and Classes
4.12 Friend function and its characteristics:
C++ supports the feature of encapsulation which binds data and functions
together. By doing this C++ ensures that data is accessible only by the functions
operating on it and not to anyone outside the class.
But in some real-time applications, sometimes we might want to access
data outside the bundled unit.
A friend function in C++ is a function that is preceded by the keyword
“friend”. When the function is declared as a friend, then it can access the private
and protected data members of the class.
A friend function is declared inside the class with a friend keyword
preceding as shown below.
class Box
{
double width;

public:
double length; //Arguments are object of same class
friend void printWidth( Box B1 );
void setWidth( double wid );
};
As shown above, the friend function is declared inside the class whose
private and protected data members are to be accessed. The function can be
defined anywhere in the code file and we need not use the keyword friend or the
scope resolution, operator.

Characteristics of a Friend function:


 The function is not in the scope of the class to which it has been declared
as a friend.
 It cannot be called using the object as it is not in the scope of that class.
 It can be invoked like a normal function without using the object.
 It cannot access the member names directly and has to use an object
name and dot membership operator with the member name.
 A friend function can be declared in either the private or public section
of the class.
 It can be called like a normal function without using the object.
 A friend function can be a global function or a member of another class.

43
Objects and Classes
/* 12 Program to demonstrate use of Friend Function*/
#include<iostream.h>
#include<conio.h>
class Addition
{
int a;
int b;
public:
void getdata()
{
cout<<"\n Enter two nos.: ";
cin>>a>>b;
}
friend void calculate(Addition f);
};
void calculate(Addition f)
{
float c;
c=f.a+f.b;
float avg;
avg=c/2;
cout<<"\n Addition: "<<c;
cout<<"\n Average : "<<avg;
}
int main()
{
clrscr();
Addition f;
f.getdata();
calculate(f);
getch();
return 0;
}

Output:

44

You might also like