[go: up one dir, main page]

0% found this document useful (0 votes)
68 views81 pages

Definition and Declaration of A Class

The document defines classes in C++ and describes how to declare and define classes, member functions, and objects. Some key points: - A class combines related data (member variables) and functions (member functions) and defines a new user-defined data type. - The class syntax includes access specifiers like private and public to define how members can be accessed. - Member functions can be defined inside or outside the class definition using the scope resolution operator ::. - Objects are instances of a class and are declared after the class definition. Member functions and variables can then be accessed using the dot operator. - Private members can only be accessed by member functions, while public members can be accessed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views81 pages

Definition and Declaration of A Class

The document defines classes in C++ and describes how to declare and define classes, member functions, and objects. Some key points: - A class combines related data (member variables) and functions (member functions) and defines a new user-defined data type. - The class syntax includes access specifiers like private and public to define how members can be accessed. - Member functions can be defined inside or outside the class definition using the scope resolution operator ::. - Objects are instances of a class and are declared after the class definition. Member functions and variables can then be accessed using the dot operator. - Private members can only be accessed by member functions, while public members can be accessed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 81

DEFINITION AND DECLARATION OF A CLASS

A class in C++ combines related data and functions together. It


makes a data type which is used for creating objects of this type.
Classes represent real world entities that have both data type
properties (characteristics) and associated operations (behavior).

The syntax of a class definition is shown below :


Class name_of _class
{
private : variable declaration; // data member
Function declaration; // Member Function (Method)
protected: Variable declaration;
Function declaration;
public : variable declaration;
Function declaration;
};

Here, the keyword class specifies that we are using a new


data type and is followed by the class name.
The body of the class has two keywords namely :
(i) private (ii) public
In C++, the keywords private and public are called access
specifiers.
The data hiding concept in C++ is achieved by using the
keyword private. Private data and functions can only be
accessed from within the class itself. Public data and
functions are accessible outside the class also.

Data hiding not mean the security technique used for


protecting computer databases. The security measure is
used to protect unauthorized users from performing any
operation (read/write or modify) on the data.
The data declared under Private section are hidden and
safe from accidental manipulation. Though the user can use
the private data but not by accident.
The functions that operate on the data are generally public
so that they can be accessed from outside the class but this
is not a rule that we must follow.

MEMBER FUNCTION DEFINITION

The class specification can be done in two part :


(i) Class definition. It describes both data members and
member functions.
(ii) Class method definitions. It describes how certain class
member functions are coded.

In C++, the member functions can be coded in two ways :


(a) Inside class definition
(b) Outside class definition using scope resolution operator
(::)

Inside Class Definition


When a member function is defined inside a
class, we do not require to place a membership
label along with the function name. We use only
small functions inside the class definition and
such functions are known as inline functions.
In case of inline function the compiler inserts the
code of the body of the function at the place
where it is invoked (called) and in doing so the
program execution is faster but memory penalty
is there.

Let us take previously defined class to access the


members of the class using a member function
instead of directly accessing them:
class Box
{
public:

double length;
// Length of a box

double breadth;
// Breadth of a box

double height;
// Height of a box

double getVolume(void);// Returns box volume


};

Member functions can be defined within the class definition or


separately usingscope resolution operator, ::. Defining a
member function within the class definition declares the
functioninline, even if you do not use the inline specifier. So
either you can defineVolume()function as below:
class Box
{
public:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
double getVolume(void)
{
return length * breadth * height;
}
};

Outside Class Definition Using Scope Resolution Operator (::)

In this case the functions full name (qualified_name) is


written as shown:
Name_of_the_class :: function_name
The syntax for a member function definition outside the
class definition is :
return_type name_of_the_class::function_name (argument
list)
{
body of function
}
Here the operator::known as scope resolution operator
helps in defining the member function outside the class.

If you like you can define same


function outside the class using
scope resolution operator, :: as
follows:
double Box::getVolume(void)
{

return length * breadth * height;


}

DECLARATION OF OBJECTS AS
INSTANCES OF A CLASS

The objects of a class are declared after the class definition. One
must remember
that a class definition does not define any objects of its type, but it
defines the properties of a class. For utilizing the defined class, we
need variables of the class type. For example,
Largest ob1,ob2; //object declaration
will create two objects ob1 and ob2 of largest class type. As
mentioned earlier, in C++ the variables of a class are known as
objects.
These are declared like a simple variable i.e., like fundamental
data types.

ACCESSING MEMBERS FROM


OBJECT(S)

After defining a class and creating a class variable i.e.,


object we can access the data members and member
functions of the class.
Because the data members and member functions are
parts of the class, we must access these using the variables
we created.
For functions are parts of the class, we must access these
using the variable we created.
Member function Example

Class student
{
private:
char reg_no[10];
char name[30];
int age;
char address[25];

public :
void init_data()
{
- - - - - //body of function
---- }
void display_data()
}
};
student ob; //class variable (object) created
---- ---- Ob.init_data(); //Access the member function
ob.display_data(); //Access the member function
- --- -----

Here, the data members can be accessed in the member


functions as these have private scope, and the member
functions can be accessed outside the class i.e., before or
after the main() function.
structure of class example

Illustrates a class declaration and


function definition in the class

#include <iostream>
class Market // Market is name of class.
{
//The { marks beginning of class declaration.
public: // Access label public
void Display() // Definition of a public function Display ()
{
cout<< Welcome To This Market << endl;
cout << Here is the price List <<endl;}
}; //Semicolon after } marks end the of class declaration.
void main() // start of main program.
{
Market L1; // declaration of object L1 of class Market
L1.Display(); // Function linked with object L1
} // dot(.) is selection operator

DEFINING A MEMBER FUNCTION


OUTSIDE THE CLASS

The above program is repeated below with the prototype of


member function declared in theclass but function is
defined outside the class body.. For defining a function
outside the class body one has to use the scope resolution
operator (::). An illustration is given below.
type class_name :: Function_name (type parameter1, - - -, - -, type parameter n)
{ statements ; } // function body
Here type refers to the type of the data returned by the
function, it is followed by name of the class, then the scope
resolution operator followed by function name and
parameters in brackets. This is followed by body of function
in braces{}

#include <iostream>
using namespace std;
class Market
{ // start of class declaration
public:
void Display(); // function prototype
}; // end of class
/*In the following function definition, void is typeof function, Market
is class name, :: is the scope resolution and Display is name of
function, there
are no parameters*/
void Market::Display () //function definition outside the class
{
cout<< Welcome To This Market << endl;
cout << Here is the price List <<endl;
}
void main() //main program
{Market L1; // L1 is declared an object of class market
L1.Display(); // L1 calls function display
}

INITIALIZING PRIVATE DATA


MEMBERS

An object of a class is constructed when its data members are


initialized. If data is declared private, the initialization is carried by a
public function which may be a constructor function.
a class has both the public members and private members. The data
members x, y and z are declared private. For accessing the private
data members we need a public function.
This is provided as Setprice (). In the class body, it is defined as below.
void Setprice (int a, int b, int c)
{x = a,y = b, z = c;}
For defining the same function outside the class body, first we have to
declare its prototype in the class as,
void Setprice (int , int , int );
and put the definition outside the class as given below.
void Market ::Setprice (int a , int b , int c )
{x = a, y = b , z = c ;}

#include <iostream>
using namespace std;
class Market
{
private :
int x,y,z;
public:
void Display1()
{
cout<< Welcome! Here is the price List << endl;}
void Setprice (int a, int b, int c) // function defined in class
{x = a, y = b, z = c;}
void Display2 ()
{
cout<< Price of item1 = << x<<endl;
cout<< Price of item2 = << y<<endl;
cout<< Price of item3 = << z<<endl;
}
}; // End of class
void main()
{
Market L1;
L1.Setprice (4,6,2); // Object L1 is initialized by function
// setprice()
L1. Display1(); // Functions called by using dot operator.
L1.Display2();
}

initializing public datamembers from outside the class.

#include <iostream>
using namespace std;
class Rect { // beginning of class
public:
int x ,y; // data declared public
int Area( )
{return x*y; }
}; // End of class
int main()
{
Rect R1; //R1 is an object of class Rect
R1.x = 8; // accessing data members directly
R1.y = 5;
cout << Area = << R1.Area()<<endl;
cout << Length = << R1.x <<endl;
cout<< Width = << R1.y << endl;
return 0 ;
}

ACCESSING PRIVATE DATAMEMBERS


The above program is repeated below, now with the data x, y
declared private. Now x and y are not accessible by the
object directly and we have to create a public function to
initialize the object data so that rectangle is realised.
This is done by public function void setsides ().
Inthis function we declare two int variables L and W and we
equate x = L and y = W. Since L and W are declared in the
public domain they are accessible to the objects of class
So in the main () we create an object R1 of the class and in
next linethe function setsides()is called and the values 8 and
5 are put in as its arguments.
These are the values of L and W which are passed on to x
and y through the function setsides(). These values of x and
y are used to calculate the area

Now if you try to access the data of the rectangle by calling


R1.x or R1.y as done in the previous Program 11.4 you
would get the following error message.
x : cannot access private member declared in class Rect
y : cannot access private member declared in class Rect

#include <iostream>
using namespace std;
class Rect {
private :
int x ,y;
public:
void setsides ( int L, int W){ x = L, y = W;}
int Area( ){return x*y;} // definition of function Area ()
// public function to get object data
void Dimension (){cout <<Length = << x <<,\tWidth = <<y
<< endl; }
}; // End of class
int main()
{
Rect R1;
R1.setsides (8,5) ; //Calling setside () to initialize x,y
cout << Area = << R1.Area()<<endl;
R1.Dimension (); // calling function Dimension ()
return 0 ;
}

ACCESSING PRIVATE FUNCTION


MEMBERS OF A CLASS

Carefully see the following program, in which, the data


members as well as functions volume()and surface_area()are
declared private. The private functions cannot be access
ddirectly from outside.
However, they can be accessed through other public member
functions and friend functions of the class. In order that the
objects could access private functions, first we have to
introduce public functions which return the values of private
functions.
The objects can access these public functions.
This is one reason that functions are generally declared public.
But the functions which are used only by class members, and, if
it is desired that these should not be visible to users of the
program, may be declared private.

#include <iostream>
using namespace std;
class Cuboid {
private:
int surface_area( ); // function declared private
int volume( ); // function declared private
int x , y, z; // data declared private
public:
Cuboid(int L,int W,int H ):x(L),y(W),z (H){} // Constructor
}; // End of class
int Cuboid::surface_area()
{return 2*(x*y +y*z +z*x);}
int Cuboid::volume()
{return x*y*z ;}
int main()
{
Cuboid C1(5,6,4);
cout << Volume of cuboid C1 << C1. volume()<<\n;
cout<< surface area of C1 = << C1. surface_area()<<\n;
return 0 ;
}

The expected output is as follows.


error : cannot access private member declared in class
Cuboid
error : cannot access private member declared in class
Cuboid

Illustrates accessing private function


member through a public member
function

#include <iostream>
class Cuboid {
private:
int surface_area( ); // private member function
int volume( ); // private member function
int x , y, z; // private data
public:
Cuboid( int L,int W,int H ):x(L),y(W),z (H){} // Constructor
int Surface_area () { return surface_area ();}
//A public function to just pass on the return values.
int Volume () { return volume();}
//The public function for passing on the return value
// Volume and volume are different because of different case of
//first letter. So are the Surface_area and surface_area
}; // End of class
int Cuboid::surface_area() // Definition of surface_area()
{return 2*(x*y +y*z +z*x);}
int Cuboid::volume() // Definition of volume
{return x*y*z ;}
int main()
{
Cuboid C1(5,6,4);
cout << Volume of cuboid C1 << C1. Volume()<<\n;
cout<<Surface area of C1 = << C1. Surface_area()<<\n;
return 0 ;
}

LOCAL CLASSES

A class declared inside a function becomes local to that


function and is called Local Class in C++. For example, in the
following program, Test is a local class in fun().
#include<iostream>
using namespace std;
void fun()
{
class Test // local to fun
{ /* members of Test class */ }
;}
int main()
{
return 0;
}

All the methods of Local classes must be defined


inside the class only
#include<iostream>
void fun()
{
class Test // local to fun
{
public:
// Fine as the method is defined inside the local class
void method() {
cout << "Local Class method() called";
}
};
Test t;
t.method();
}
int main()
{
fun();
return 0;
}
Output:
Local Class method() called

#include<iostream>
void fun()
{
class Test // local to fun
{
public:
void method();
};
// Error as the method is defined outside the local class
void Test::method()
{
cout << "Local Class method()";
}
}
int main()
{
return 0;
}
Output:
Compiler Error:

In function 'void fun()':

error: a function-definition is not allowed here before '{' token

CONSTANT OBJECTS

It is good programming practice to make an object constant


if it should not be changed. This is done with the const
keyword:
const char BLANK = ' ';
const int MAX_INT = 2147483647;
const double PI = 3.141592653589793;
void init(float a[], const int SIZE);
Like variables and function parameters, objects may also be
declared to be constant:
const Ratio PI(22,7);

In fact, unless we modify our class definition, the only member


functions that could be called for const objects would be the
constructors and the destructor.
To overcome this restriction, we must declare as constant
those member functions that we want to be able to use with
const objects.
A function is declared constant by inserting the const keyword
between its parameter list and its body:
Const class Member function
A const member function never modifies data members in an
object.
Syntax :
return_type function_name() const;
void print() const { cout << num << '/' << den << endl; }

class X
{
int i;
public:
X(int x) // Constructor
{
i=x;
}
int f() const // Constant function
{
i++;
}
int g()
{ i++; }
};
int main()
{
X obj1(10); // Non const Object
const X obj2(20); // Const Object
obj1.f(); // No error
obj2.f(); // No error
cout << obj1.i << obj2.i ;
obj1.g(); // No error
obj2.g(); // Compile time error
}
Output : 10 20

Here, we can see, that const member


function never changes data
members of class, and it can be used
with both const and non-const object.
But a const object can't be used with
a member function which tries to
change its data members

Constructor & destructor

A constructor function is a public function and has same name as


that of the class.
It is used to initialize the object data variables or assign dynamic
memory in the process of creation of an object of the class so that
the object becomes operational.
Whenever a new instance or an object of the class is declared the
constructor is automatically invoked and allocates appropriate size
of memory block for the object.
The constructor function simply initializes the object. It does not
return any value. It is not even void type. So nothing is written for
its type.

Constructor function has same name as that of the class.


(ii) It is declared as a public function.
(iii) It may be defined inside the class or outside the class. If
it is defined outside the class
its prototype must be declared in the class body.
(iv) It does not return any value, nor it is of typevoid. So no
typeis written for it.
(v) The constructor is automatically called whenever an
object is created.

Declaration and Definition of a


Constructor

It is defined like other member functions of the class, i.e.,


either inside the class definition or outside the class
definition

//To demonstrate a constructor


#include <iostram.h>
#include <conio.h>
Class rectangle
{
private :
float length, breadth;
public:
rectangle ()//constructor definition
{
//displayed whenever an object is created cout<<I am in the constructor;
length=10.0;
breadth=20.5;
}
float area()
{
return (length*breadth);
}
};
void main()
{
clrscr();
rectangle rect; //object declared
cout<<\nThe area of the rectangle with default parameters
is:<<rect.area()<<sq.units\n;
getch();
}

Type Of Constructor

There are different type of constructors in C++.


Overloaded Constructors
Besides performing the role of member data initialization,
constructors are no different from other functions. This included
overloading also. In fact, it is very common to find overloaded
constructors.

Example of overloaded constructors

Copy Constructor
It is of the form classname (classname &) and used for
the initialization of an object form another object of
same type. For example
A copy constructor may be called in the following
situations:
1. When an object is defined and initialized with other
object of the same class.
Eg:
sample s1;
sample s2=s1;
2. When we pass an object by value.
3. In case a function returns an object.

#include<iostream>
#include<conio.h>
class Example
{
int a,b; // Variable Declaration
public:
Example(int x,int y)
{
a=x;
b=y;
cout<<"\nIm Constructor";
}
void Display() {
cout<<"\nValues :"<<a<<"\t"<<b;
}
};
int main()
{
Example Object(10,20);
//Copy Constructor
Example Object2=Object;
// Variable Declaration
Object.Display();
Object2.Display();
// Wait For Output Screen
getch();
return 0;
}

#include <iostream.h>
class Exforsys()
{
private: int a;
public: Exforsys()
{}
Exforsys(int w)
{ a=w; }
Exforsys(Exforsys& e)
{
a=e.a;
cout<< Example of Copy Constructor;
}
void result()
{
cout<< a;
}
};
void main()
{ Exforsys e1(50);
Exforsys e3(e1);
cout<< \ne3=;
e3.result();
}

Default Constructor:

This constructor has no arguments in it. Default Constructor is also called as


no
argument constructor.
class Exforsys
{
private:
int a,b;
public:
Exforsys(); //default Constructor
...
};
Exforsys :: Exforsys()
{
a=0;
b=0;
}

Parameterized Constructor

A parameterized constructor is just one that has parameters specified in it


Example:
class Exforsys
{
private:
int a,b;
public:
Exforsys(int,int);// Parameterized constructor
...
};
Exforsys :: Exforsys(int x, int y)
{
a=x;
b=y;
}

Some important points about constructors:


A constructor takes the same name as the class name.
The programmer cannot declare a constructor as virtual
or static, nor can the programmer declare a constructor as
const, volatile, or const volatile.
No return type is specified for a constructor.
The constructor must be defined in the public. The
constructor must be a public member.
Overloading of constructors is possible.

What is the use of


Destructors

Destructors are also special member functions used in


C++ programming language.
Destructors have the opposite function of a constructor. The
main use of destructors is to release dynamic allocated
memory.
Destructors are used to free memory, re lease
resources and to perform other clean up.
Destructors are automatically called when an object is
destroyed. Like constructors, destructors also take the
same name as that of the class name.

General Syntax of Destructors


~ classname();
The above is the general syntax of a destructor. In the
above, the symbol tilda ~ represents a destructor which
precedes the name of the class

Some important points about destructors:


Destructors take the same name as the class name.
Like the constructor, the destructor must also be defined
in the public. The destructor must be a public member.
The Destructor does not take any argument which
means that destructors cannot be overloaded.
No return type is specified for destructors.

For example:
class Exforsys
{
private:

public:
Exforsys()
{}
~ Exforsys()
{}}
Constructor and Destructor Example

STATIC CLASS MEMBERS


Data members and member functions of a class in C++, may
be qualified as static. We can have static data members and
static member function in a class
Static Data Member: It is generally used to store value
common to
the whole class. The static data member differs from an
ordinary data member in the following ways :
(i) Only a single copy of the static data member is used by all
the objects.
(ii) It can be used within the class but its lifetime is the whole
program.
For making a data member static, we require :
(a) Declare it within the class.
(b) Define it outside the class.

For example
Class student
{
Static int count; //declaration within class
------------------------------------------------};
The static data member is defined outside the class as :

int student :: count; //definition outside class

The definition outside the class is a must.

We can also initialize the static data member at the time of its definition as:

int student :: count = 0;

If we define three objects as : student obj1, obj2, obj3;

Static Datamember Example

Static Function Members

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 thestaticfunctions 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.

Class student
{
Static int count;
----------------public :
--------------------------------static void showcount (void) //static member function
{
Cout<<count=<<count<<\n;
}
};
int student ::count=0;
Static Member Function Example

STRUCTURES

Structures (a legacy from C language) also give facility to


organize related data items in a single unit.
It is a user defined data type containing logically related
data but which may be of different typeslike int, double,
char, arrays or strings. All of them are encapsulated in a
unit.
For example, suppose it is required to prepare list of
students along with their data like name, registration
number, age, address, etc. This can be done easily by
designing a structure of relevant data.
Each student is related to his/her structure, in fact, a
structure represents a student.
The data items are called members of the structure

The classes are in fact generalization of structures. A class


with only public members is like a structure.
All members of a structure are by default public.
However, in a class declaration, if there is no access
specifier, the members are by default private. But in C++
structures the access specifier as well as functions may be
used
It starts with the keyword struct followed by its name and
statements are enclosed between curly braces { } and a
semi-colon after the closing right brace ( }).
The declaration does not contain any access specifier. The
structure is made for employees of a company.

struct Employee // Employee is name of struct


{ char Name [30];
int Age;
char Designation [25];
int Pay ;
};
Each employee may have an employee-code number such as E1,
E2, E3, etc. The code may be used to represent the structure of a
particular employee. In a program the codes E1, E2, etc., may be
defined as an object of type Employee. It is illustrated below.
Employee E1, E2, E3 ;
The above definition allocates enough memory for each of E1, E2
and E3 for storing their respective data. Note that the
declarations of E1, E2, E3 etc

ACCESSING STRUCTURE
MEMBERS

The members of a structure are public by default and hence


can be accessed by objects or instances directly.
In the above structure, for instance, the relevant data about
an employee may be extracted by using dot (.) operator as
it is done for a class object.
For instance, if the name, designation and pay of the
employee with the code E3 are to be obtained, it is coded
as illustrated below.
E3.Name ; // The dot ( . ) operator provides the link.
E3.Designation ;
E3.Pay ;

INITIALIZATION
Initialization cannot be done inside the structure declaration
because that is a kind of blue-print or design.
The particular instances may be initialized as illustrated below
for the case of struct Employee. The method of accessing the
individual structure is illustrated above.
If it is desired to initialize the name of employee for instance,
we can write
E1.Name = Ram Dass;
The whole structure may be initialised as illustrated below.
Employee E1, E2, E3;
E1 = { Ram Dass, 30, Engineer, 20000};
E2 = {Dinesh, 25, Jr-Engineer, 15000};
E3 = {Priti, 20 , Office Manager, 1500};
A structure may be assigned to another structure.

# include <iostream>
using namespace std;
struct Employee // declaration of structure Employee.
{
char Name [30];
int Age;
char Designation [25];
int Pay ;}; // End of structure
int main ()
{ Employee E1 = { Ram Dass, 30, Engineer, 20000};
Employee E2 = {Dinesh, 25, Jr-Engineer, 15000};
Employee E3 = {Priti, 20 , Office Manager, 1500};
cout<< The data of employee E2 is :\n;
cout<< Pay <<E2.Pay<<endl;
cout<< Name << E2.Name<<endl;
cout << Age << E2.Age <<endl;
cout<< Designation << E2.Designation<<endl;
return 0;
}

The expected output is given below.


The data of employee E2 is :
Pay 15000
Name Dinesh
Age 25
Designation Jr-Engineer

A structure may be assigned to another structure

# include <iostream>
using namespace std;
struct Employee
{ char Name [30];
int Age;
char Designation [25];
int Pay ;}; // end of declaration
int main ()
{ Employee E1 = { Ram Dass, 30, Engineer, 20000};
Employee E2 = { Dinesh, 25, Jr-Engineer, 15000};
Employee E3 = { Priti, 20 , Office Manager, 15000};
cout<< The data of employee E2 is :\n;
cout<< Pay <<E2.Pay<<endl;
cout<< Name << E2.Name<<endl;
cout << Age << E2.Age <<endl;
cout<< Designation << E2.Designation<<endl;
E1 = E3; // assignment of structure
cout<< Pay <<E1.Pay<<endl;
cout<< Name << E1.Name<<endl;
cout << Age << E1.Age <<endl;
cout<< Designation << E1.Designation<<endl;
return 0;
}

The expected output is given below.


The data of employee E2 is :
Pay 15000
Name Dinesh
Age 25
Designation Jr-Engineer
Pay 15000
Name Priti
Age 20
Designation Office Manager

C++ STRUCTURES

In C++ structures, the access specifier as well as functions


may be used. There is little difference between a class and
a structure. We may use a constructor function as in classes

#include<iostream>
#include <string>
using namespace std;
struct Employee
{
private :
int Pay, Employee_code ;
public:
Employee ( int E,int P ) { Employee_code =E , Pay = P ;}
// constructor function
int getpay ( ) {return Pay ;} // functions
int getcode (){return Employee_code ;}
};
int main ()
{
Employee E1 (22, 10000);
Employee E2 (32, 15000);
cout<< Employee_code of E1 = << E1.getcode ()<<endl;
cout<< Pay of E1 = <<E1.getpay()<<endl;
cout<< Employee_code of E2 = << E2.getcode ()<<endl;
cout<< Pay of E2 = <<E2.getpay()<<endl;
return 0;
}

The expected output is given below.


Employee_code of E1 = 22
Pay of E1 =10000
Employee_code of E2 = 32
Pay of E2 =15000

POINTER TO A CLASS

Pointer to a class may be declared in the same way as it is


done for integer or double numbers.
Let us have a class by name List and let L1 be an object of
this class. Let ptr be the pointer to the class. For declaration
of pointer to List we may write the code as below.
List L1 ;// declaration that L1 is an object of class List
List *ptr;// declaration of pointer to List
ptr = &(List) L1;// assignment of value to ptr
The last line may as well be written as ptr = &List (L1);

Illustrates definition of a pointer to a


class

pointer to a class
The above program also shows that for calling a function of
class in the main ()through a pointer ptr, either of the
following two codes may be used.
ptr -> Display3();
or
(*ptr).Display3();
Both the above statements are equivalent. In the second
statement *ptr has to be enclosed in brackets because the
dot (.) operator has higher precedent than the dereference
operator (*).

POINTERS TO OBJECTS OF A
CLASS

Let L1 be an object of class list, the pointer to L1 may be


declared and assigned as below.
List *ptr = &L1;
POINTERS TO OBJECTS OF A CLASS

What is a Friend
Function?

A friend function is used for accessing the non-public


members of a class. A class can allow non-member
functions and other classes to access its own private data,
by making themfriends. Thus, a friend function is an
ordinary function or a member of another class.

The Need for Friend


Function:

As discussed in the earlier sections on access specifiers,


when a data is declared as private inside a class, then it is
not accessible from outside the class. A function that is not
a member or an external class will not be able to access the
private data.
Aprogrammermay have a situation where he or she would
need to access private data from non-member functions
and external classes. For handling such cases, the concept
of Friend functions is a useful tool.
Also a friend function is not a member function of the class
in which it is declared as friend, and hence a friend function
is defined outside the class body

How to define and use Friend


Function in C++:

The friend function is written as any other normal function,


except the function declaration of these functions is
preceded with the keyword friend. The friend function must
have the class to which it is declared as friend passed to it
in argument.

Some important points to note while using


friend functions in C++:
The keyword friend is placed only in the function declaration of
the friend function and not in the function definition.
It is possible to declare a function as friend in any number of
classes.
When a class is declared as a friend, the friend class has
accessto the private data of the class that made this a friend.
A friend function, even though it is not a member function,
would have the rights to access the private members of the
class.
It is possible to declare the friend function as either private or
public.
The function can be invoked without the use of an object. The
friend function has its argument as objects, seen in example
below.

The declaration of prototype of a friend function in the class body


is illustrated below. It starts with keyword friend followed by the
type of function and identifier (name) for the function which is
followed by a list of types of parameters of the function enclosed
in parentheses ().
It ends with a semicolon.
friendtype
identifier(type_parameter1,type_parameter2, ..);
For instance, a function with name Area()is declared a friend
function of class Rect which is a class for rectangular figures
having sides x and y as under.
friend int Area(const Rect &b);
In the above declaration the data of the object b of class Rect are
the only parameters of the function, however, a friend function
may have other parameters as well.

Without Friend Function

Class A
{
int a;int b;
public:
void set_value(int m,int n)
{
a=m;
b=n; }
void put_value()
{ cout<<m<<n; }
};
int square( A &x)
{int t=x.a *x.a + x.b*x.b; /* error.
accessing private data members of object*/
return t;
}

Using Friend Function:


Class A
{ int a; int b;
public:
void set_value(int m,int n)
{ a=m; b=n; }
void put_value()
{ cout<<a<<b; }
friend void square( A &x);
};
void square( A &x)
{int t; t=x.a *x.a + x.b*x.b; return t;}
void main()
{ A objA; int i=15;int j=30;
objA.setvalue(i,j);
objA.putvalue();
cout<<Sum of Squared value
is<<square(objA);
}

The expected output is given below.


Area of R1= 30
Area of R2 = 12
In the above program the friend function takes all the
arguments from the data of objects of the class.
One of the object R1 has the dimensions 5 and 6, the friend
function gives the area 30 while the second object R2 has
the dimensions 3 and 4 and its area is given out as 12.
The output shows that friend function can access the
private data members of the class.

ONE FUNCTION FRIEND OF MANY


CLASSES

A function may be friend to many classes. This is illustrated


in the following program in which a function Display() is
declared friend to two classes, i.e. class Sqr and class Rect.
Example

FRIEND CLASSES

When all or most of the functions of a class need access to


data members and function members of another class, the
whole class may be declared friend to the class.
For instance, if the functions of a class say class A need to
access the public, private and protected members of
another class say class B, the class A may be declared as
friend class A ;in the body of class B.
As you know friend is a keyword of C++. The declaration is
illustrated below.

Class B
{
friend class A; //declaration that class A is friend of B
private:
statements
friend class C; //declaration that class C is friend of B
public:
Other_statements;
}
Example

Friend-Rules

Friend Function is not in the scope of the class to which it


has been
declared as friend
It cannot be called using the object of the class
Invoked like normal function
It cannot access members name directly and has to use
an object name
and dot membership operator with each member name.
(A.x);
Can be declared in either public or private section
Usually it has the objects as arguments
Usually used in operator overloading
Member function of one class can be friend functions of
another class

friend function act as bridge between 2 class

friend function act as bridge between


2 class

You might also like