0% found this document useful (0 votes)
54 views

CPP Lecture Notes - Unit 2

Non

Uploaded by

sajimonksajeev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

CPP Lecture Notes - Unit 2

Non

Uploaded by

sajimonksajeev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

LECTURE NOTE

University : Mahatma Gandhi University


Programme Name : BCA
Semester : Two
Course Name : Object Oriented Programming using C++
Course Code : CA2CRT06

UNIT – 2
CLASSES AND OBJECTS

Syllabus
Specifying a class- Defining member functions- Nesting of member functions -
Private member functions - Arrays within a class - Memory allocation for
objects-Static data members - Static member functions -Arrays of objects -
objects as function arguments -Friendly functions- Returning Objects.

Book of Study
• E. Balagurusamy - Object Oriented Programming with C++, Fifth edition, Tata
McGraw Education Hill , 2011.
• Ashok N. Kamthane, Object oriented Programming with ANSI & Turbo C++, First
Edition, Pearson India
Object Oriented Programming using C++ Unit 2

Structures in C
A structure is a convenient tool for handling a group of logically related data items. It is
a user defined data type with a template. Once the structure type has been defined, we can
create variables of that type using declarations, that are similar to the built-in type declarations.
Consider the example:
struct student
{
char name[20];
int roll_number;
float total_marks;
};
Here, the keyword struct declares student as a new data type that can hold three fields of
different data types.

struct student A; // C declaration

Classes –Specifying a Class


Class is an extension of the idea of structure used in C. It is a new way of creating and
implementing a user-defined data type. 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.
A Class specification has two parts:
• Class Declaration
• Class Function Definitions
Class Declaration
class class_name
{
private :
variable declarations;
function declarations;
public :
variable declarations;
function declarations;
};
The class declaration is similar to a struct declaration. The body of a class is
enclosed within braces and terminated by a semicolon. The class body contains the declaration
of variables and functions. These functions and variables collectively called class members.

Members grouped into two sections:


private
public

1
Object Oriented Programming using C++ Unit 2

The keywords are followed by colon. The class members that have been declared as private
can be accessed only from within the class. public members can be accessed from outside
the class also. Keyword private is optional. By default, the members of a class are
private.

The variables declared inside the class are known as data members and the functions
are known as member functions. Only the member functions can have access to the private
data members and private functions. The public members (both functions and data) can be
accessed from outside the class. The binding of data and functions together into a single class-
type variable is referred to as encapsulation.
Class Example
class item
{
int number; // variable declaration
float cost; // private by default
public :
void getdata( int a, float b);// function declaration
void putdata( void ); // using prototype
};
Give meaningful names to classes. Names become the new type identifier that can be
used to declare instances of that class type. The class item contains two data members and two
member functions. The data members are private by default, while both the functions are
public by declaration. The functions are declared but not defined. Actual function definition
will appear later in the program.

Creating Objects
Once a class has been declared, we can create variables of that type by using the class
name.
item x ; // create a variable x of type item.
In C++, the class variables are known as objects.
item x, y, z ; // declare more than one objects in one statement
The declaration of an object is similar to that of any basic type. The necessary memory space is
allocated to an object at this stage. Class specification, like a structure, provides only a
template and does not create any memory space for the objects. Object can also be created
when a class is defined by placing their names immediately after the closing brace.
class item
{
……
……
……
} x, y, z ;

2
Object Oriented Programming using C++ Unit 2

Accessing Class Members


The private data of a class can be accessed only through the member functions of that
class.
object-name . function-name ( actual-arguments);
In our example, although x is an object of the type item to which number belongs, the
number can be accessed only through a member function and not by the object directly.

Defining Member Functions


Member functions can be defined in two places:

Outside the class definition.


Inside the class definition.
Outside the Class Definition
Member functions that are declared inside a class have to be defined separately outside
the class. Their definitions are very much like the normal functions. They should have a
function header and a function body. An important difference between a member function and
a normal function is that a member function incorporates a membership “identity label” in the
header.

return-type class-name : : function-name (argument declaration)


{
Function body
}
The membership label class-name : : tells the compiler that the function function-
name belongs to the class class-name. The scope of the function is restricted to the class-
name specified in the header line.
Example:
#include <iostream.h>
class Example
{
private:
int val;
public:
void init_val(int v); //function declaration
void print_val(); //function declaration
};
void Example::init_val(int v) //function definitions

{
val=v;
}

3
Object Oriented Programming using C++ Unit 2

void Example::print_val()
{
cout<<"val: "<<val<<endl;
}
int main()
{

Example obj; //create object


obj.init_val(25);
obj.print_val();
return 0;
}
Output
val: 25
Inside the Class Definition
Replace the function declaration with the definition of the function inside the class.
When a function is defined inside a class, it is treated as an inline function. All the restrictions
and limitations that apply to an inline function are also applicable to the functions defined
inside a class.
Syntax:
class class_name
{
private:
declarations;
public:
function_declaration(parameters)
{
function_body;
}
};
Example:
#include <iostream.h>
class Example
{
private:
int val;
public:

void init_val(int v) //function to assign value


{
val=v;
}

void print_val()//function to print value


{
cout<<"val: "<<val<<endl;

4
Object Oriented Programming using C++ Unit 2

}
};
int main()
{

Example Ex; //create object


Ex.init_val(25);
Ex.print_val();

return 0;
}
Output
val: 25

Making an Outside Functions Inline


Inline function is a function which when invoked requests the compiler to replace the
calling statement with its body. A keyword inline is added before the function name to make it
inline. It is an optimization technique used by the compilers as it saves time in switching
between the functions otherwise. Member functions of a class are inline by default even if the
keyword inline is not used.

Syntax
inline return_type function_name ([argument list])
{
body of function
}
The member functions defined outside a class can be made inline by using the qualifier
inline in the header line of function definition.

class item
{
……
……
public :
void getdata (int a, float b);
};
inline void item : : getdata (int a, float b)
{
number = a ;
cost = b ;
}
Some of the situations where inline expressions may not work are:
1. For functions returning values, if a loop, a switch, or a goto exists.

5
Object Oriented Programming using C++ Unit 2

2. For functions not returning values, if a return statement exists.


3. If function contain static variables.
4. If inline functions are recursive.
Nesting of Member Functions
The member function of a class can be called only by an object of that class using a dot
operator. But a member function can be called by using its name inside another member
function of the same class. This is known as nesting of member functions.
#include<iostream.h>
class num{
int a;
int b;
public:
void get(int, int);
int add();
void avg();
};
void num::get(int x, int y) {
a=x;
b=y;
}
int num::add() {
return (a+b);
}
void num::avg() {
int s=add(); //nesting of membership function
float avg=(float)s/2;
cout<<"Avg is "<<avg;
}
int main() {
num obj;
obj.get(10,15);
obj.avg();
return 0;
}
Private Member Functions
Private member functions can be created for making them to be hidden. A private
member function can only be called by another function that is a member of its class. Even an
object cannot invoke a private function using the dot operator.

class product
{
int code ;
float stock ;
void read ( void ) ;

6
Object Oriented Programming using C++ Unit 2

public :
void update( void ) ;
void display( void ) ;
};
If p1 is an object, then
p1.read ( ) is illegal.
However, the function read( ) can be called by any of the public functions of this class.
void product : : update ( void)
{
read ( ) ;
};
Arrays within a Class
The arrays can be used as member variables in a class.

const int size = 10;


class matrix
{
int mat [ size ] ;
public:
void getval ( ) ;
void putval ( ) ;
};

Memory Allocation for Objects


The member functions are created and placed in the memory space only once when
they are defined. Since all the objects belongs to that class use the same member functions, no
separate space is allocated for member functions when the objects are created. Only space for
member variables is allocated separately for each object. Separate memory locations for the
objects are essential, because the member variables hold different data values for different
objects.

Static Data Members


A data member of a class can be qualified as static. Characteristics of static member variables:
• 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 the
objects of that class, no matter how many objects are created.
• It is visible only within the class, but its lifetime is the entire program.
Static variables are normally used to maintain values common to the entire class. The
type and scope of each static member variable must be defined outside the class definition.

7
Object Oriented Programming using C++ Unit 2

This is because the static data members are stored separately rather than as a part of an object.
Since they are associated with class itself rather than with any class object, they are also known
as class variables.
Static variables are like non-inline member functions as they are declared in a class
declaration and defined in the source file. While defining a static variable, some initial value
can also be assigned to the variable.

type class-name : : static-variable = initial value;

Example:- Static Data Member

#include<iostream.h>
class item {
static int count;
int num;
public:
void getdata(int a) {
num=a;
count++;
}
void getcount() {
cout<<"\n Count="<<count;
}
};
int item:: count;
int main() {
item a,b,c;
cout<<"\n Before reading data. ... ";
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<"\nAfter reading data.... ";
a.getcount();
b.getcount();
c.getcount();
return 0;
}

The output of the above program is

8
Object Oriented Programming using C++ Unit 2

Before reading data....


Count=0
Count=0
Count=0
After reading data....
Count=3
Count=3
Count=3

Static Member Functions


Like static member variable, we can also have static member functions.
Example:- Static Member Function
Class student
{
Static int count;

public :

static void showcount (void) //static member function


{
cout<<”count=”<<count<<”\n”;
}
};
int student ::count=0;
Here we have put the keyword static before the name of the function shwocount()
Properties of member functions:
A static function can have access to only other static members ( functions or variables ).
A static member function can be called using the class name ( instead of its objects ) as:
class-name : : function-name;
For example, student::showcount();
Arrays of Objects
class employee
{
char name [30];
float age;
public:
void getdata (void);
void putdata (void);
};
employee manager [5];

9
Object Oriented Programming using C++ Unit 2

Arrays of variables that are of type class are called arrays of objects.
employee worker [25];
The array manager contains five objects, viz manager[0], manager[1], manager[2],
manager[3] & manager[4]. Array of objects behave like any other array. manager [i].
putdata( ); to execute the putdata( ) member function of the ith element of the array
manager.
Example:- Array of Objects
#include<iostream.h>
class stud
{
char name[20];
int rno;
int tmark;
public:
void getdata()
{
cout<<"\nENTER NAME , ROLL NO: & TOTAL MARK\n";
cin>>name>>rno>>tmark;
}
void show()
{
cout<<"\n\t"<<name<<"\t "<<rno<<"\t\t"<<tmark;
}
};
int main()
{
stud obj[5];
int i;
for(i=0;i<5;i++)
{
obj[i].getdata();
}
cout<<"\n\tNAME\tROLL NO:\tTOTAL MARK\n";
for(i=0;i<5;i++)
{
obj[i].show();
}
return 0;
}

Objects as Function Arguments


An object can be used as a function argument like any other data type. Two ways:

A copy of the entire object is passed to the function. ( Pass-by-Value)


Only the address of the object is transferred to the function. (Pass-by-Reference)
The pass-by-reference method is more efficient since it requires to pass only the
address of the object and not the entire object. An object can also be passed as an argument to a
non-member function. Such functions can have access to the public member functions only
through the objects passed as arguments to it. These functions cannot have access to the private
data members.

10
Object Oriented Programming using C++ Unit 2

Example- Object as Function Argument

#include<iostream.h>
class num{
int a;
int b;
public:
void get(int, int);
void show(num);
};
void num::get(int x, int y) {
a=x;
b=y;
}
void num::show(num o1) { //Object as function argument
cout<<"\n o1.a= "<<o1.a;
cout<<"\t o1.b= "<<o1.b;
cout<<"\n o2.a= "<<a;
cout<<"\t o2.b= "<<b;
}
int main() {
num o1,o2;
o1.get(10,20);
o2.get(20,30);
o2.show(o1);
return 0;
}
Output of the program is
O1.a=10 o1.b=20
O2.a=30 02.b=40

Friend Functions
The private members cannot be accessed from outside the class. That is, non-member
function cannot have an access to the private data of a class. However, C++ allows a common
function to be made friendly with more than one classes, thereby allowing the function to have
access to the private data of these classes. Such a function need not be a member of these
classes.
To make an outside function friendly to a class, we have to simply declare this function
as a friend of the class. The function declaration should be preceded by the keyword friend.
The function is defined elsewhere in the program like a normal C++ function. The function
definition does not use either the keyword friend or the scope operator : :
class employee

11
Object Oriented Programming using C++ Unit 2

{
---
---
public :
---
friend void calc(void);
}
The functions that are declared with the keyword friend are known as friend function.
A function can be declared as a friend in any number of classes. A friend function, although
not a member function, has full access right to the private members of the class.
Special Characteristics:
1. It is not in the scope of the class to which it has been declared as friend.
2. Since it is not in the scope of the class, it cannot be called using the object of the class.
3. It can be invoked like a normal function without the help of any object.
4. Unlike member functions, it cannot access the member names directly and has to use an
object name and dot membership operator with each member name.
5. It can be declared either in the public or private part of a class without affecting its
meaning.
6. Usually, it has objects as arguments.
Member function of one class can be friend functions of another class. In such cases, they are
defined using the scope resolution operator as:
class X
{

int fun1 ( );

};
class Y
{

friend int X : : fun1 ( );

};

Friend Class
We can also declare all the member functions of one class as the friend functions of
another class. In such cases, the class is called a friend class.
class Z
{

friend class X ;

};
Friend function Example

12
Object Oriented Programming using C++ Unit 2

#include <iostream.h>
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d) //function definition
{
d.meter=10; //accessing private data from non-member function
return d.meter;
}
int main()
{
Distance D;
cout<<"Distace: "<<func(D);
return 0;
}
Output
Distace:10

Returning Objects
A function can also return objects either by value or by reference. When an object is
returned by value from a function, a temporary object is created within the function, which
holds the return value. This value is further assigned to another object in the calling function.
The syntax for defining a function that returns an object by value is
class_name function_name (parameter_list)
{
// body of the function
}
Example-
#include<iostream.h>
class num{
int a;
int b;
public:
void get(int, int);
num add(num);
void show();
};
void num::get(int x, int y) {

13
Object Oriented Programming using C++ Unit 2

a=x;
b=y;
}
num num::add(num obj1) {
num temp;
temp.a=a+obj1.a;
temp.b=b+obj1.b;
return temp;
}
void num::show() {
cout<<”\n o2.a=”<<a;
cout<<”\t o2.b=”<<b;
}
int main() {
num o1,o2;
o1.get(10,20);
o2.get(20,30);
o2=o2.add(o1);
o2.show();
return 0;
}
The output of the above program is
o2.a=30 o2.b=50

In the case of returning an object by reference, no new object is created, rather a


reference to the original object in the called function is returned to the calling function. The
syntax for defining a function that returns an object by reference is
class_name& function_name (parameter_list)
{
//body of the function
}

14

You might also like