structures, classes and objects handling data and objects unit - 03

50
Structures, Structures, Classes and Classes and Objects Objects Handling data and objects Handling data and objects Unit - 03 Unit - 03

Upload: neil-austin

Post on 13-Dec-2015

232 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Structures, Classes and Objects Handling data and objects Unit - 03

Structures, Structures, Classes and Classes and

ObjectsObjectsHandling data and objectsHandling data and objects

Unit - 03Unit - 03

Page 2: Structures, Classes and Objects Handling data and objects Unit - 03

Unit IntroductionUnit Introduction

This unit covers structures, classes This unit covers structures, classes and objectsand objects

Page 3: Structures, Classes and Objects Handling data and objects Unit - 03

Unit ObjectivesUnit Objectives

After covering this unit you will After covering this unit you will understand…understand…

StructuresStructures ClassesClasses Static data and member functionsStatic data and member functions Differences between structures and Differences between structures and

classesclasses ReferencesReferences Friend functions and classesFriend functions and classes

Page 4: Structures, Classes and Objects Handling data and objects Unit - 03

StructuresStructures

Following will be discussed in order Following will be discussed in order to understand structures:to understand structures: Declaration Declaration DefinitionDefinition Using structuresUsing structures Nested structuresNested structures

Page 5: Structures, Classes and Objects Handling data and objects Unit - 03

Declaring StructuresDeclaring Structures structstruct keyword is used for declaration keyword is used for declaration A structure is collection of variables A structure is collection of variables

and methodsand methods In a structure, variables can have In a structure, variables can have

different data typesdifferent data types Can have private, protected and public Can have private, protected and public

access specifiersaccess specifiers The default access specifier is The default access specifier is publicpublic Semicolon “;” comes in the end to Semicolon “;” comes in the end to

complete structure declarationcomplete structure declaration

Page 6: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Declaring Example: Declaring StructuresStructures

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

struct SPartstruct SPart

{{

private:private:

int partType; int partType; // type of part, by default public// type of part, by default public

public:public:

float cost; float cost; // cost of part, be default public// cost of part, be default public

int GetPartType()int GetPartType()

{{

return partType;return partType;

}}

}; }; // semicolon indicates end of declaration// semicolon indicates end of declaration

Page 7: Structures, Classes and Objects Handling data and objects Unit - 03

Defining StructuresDefining Structures

With declarationWith declaration A structure can be defined while declaring A structure can be defined while declaring

the structurethe structure Structure Tag (which is used to name the Structure Tag (which is used to name the

structure) is not required, if a structure structure) is not required, if a structure variable is defined while declaring the variable is defined while declaring the structurestructure

Without declarationWithout declaration Structures can be defined separately after Structures can be defined separately after

declarationdeclaration

Page 8: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Defining Example: Defining StructuresStructures// declaring and defining together// declaring and defining together

structstruct // tag is not required here// tag is not required here

{{

int partType; int partType; // type of part// type of part

float cost; float cost; // cost of part// cost of part

} part;} part; // declared and defined// declared and defined

// declaring and defining separately// declaring and defining separately

struct SMachine struct SMachine // tag is required to define it separately// tag is required to define it separately

{{

int machineType; int machineType; // type of machine// type of machine

float cost;float cost; // cost of machine// cost of machine

};}; // declared only// declared only

SMachine machine; SMachine machine; // defined now// defined now

Page 9: Structures, Classes and Objects Handling data and objects Unit - 03

Using StructuresUsing Structures Structure can be initialised either by: Structure can be initialised either by:

putting values in it; orputting values in it; or assigning other structure of same typeassigning other structure of same type

A structure variable can be assigned A structure variable can be assigned to other if they are instance of same to other if they are instance of same structurestructure

Assigning different structure types Assigning different structure types (even though they have exactly the (even though they have exactly the same data types) is not allowed and same data types) is not allowed and will generate an errorwill generate an error

Page 10: Structures, Classes and Objects Handling data and objects Unit - 03

Using Structures (contd.)Using Structures (contd.) Structures are initialised using Structures are initialised using

curly bracescurly braces Dot (Dot (..) operator is used to access ) operator is used to access

the variablesthe variables

Page 11: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Using Example: Using StructuresStructures

// Initialising a structure variables// Initialising a structure variables

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

struct SPartstruct SPart

{{

int partType; int partType; // type of part// type of part

float cost; float cost; // cost of part// cost of part

};};

void main()void main()

{{

SPart part1 = {12,23.56}; SPart part1 = {12,23.56}; // Initializing variables// Initializing variables

SPart part2;SPart part2;

part2 = part1;part2 = part1;

part2.cost = 13.5f;part2.cost = 13.5f; // cost variable accessed// cost variable accessed

}}

Page 12: Structures, Classes and Objects Handling data and objects Unit - 03

StructuresStructures Nesting can be to any level (nth Nesting can be to any level (nth

level)level) Dot (Dot (..) operator is used to access ) operator is used to access

the each inner levelthe each inner level When the inner most level is When the inner most level is

reached, the dot (.) operator will reached, the dot (.) operator will be used to access the variables be used to access the variables and functions and functions

Page 13: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Nested Example: Nested StructuresStructures

// Example of Structure nesting// Example of Structure nesting

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

struct SDistancestruct SDistance

{{

int feet; int feet;

float inches;float inches;

};};

struct SRoomstruct SRoom

{{

SDistance length;SDistance length;

SDistance width;SDistance width;

};};

Page 14: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Nested Structures Example: Nested Structures (contd.)(contd.)

void main()void main()

{{

SRoom dining = {{10,120},{10,120}} SRoom dining = {{10,120},{10,120}} // Initializing// Initializing

SRoom study; SRoom study;

study.length.feet = 10; study.length.feet = 10; // Assigning values// Assigning values

study.length.inches = 120;study.length.inches = 120;

study.width.feet = 10;study.width.feet = 10;

study.width.inches = 120;study.width.inches = 120;

}}

Page 15: Structures, Classes and Objects Handling data and objects Unit - 03

Classes in C++ Classes in C++

Following will be discussed in order Following will be discussed in order to understand Classes in C++:to understand Classes in C++: Classes and objectsClasses and objects Access specifiersAccess specifiers Member functionsMember functions ConstructorsConstructors DestructorsDestructors Static class dataStatic class data

Page 16: Structures, Classes and Objects Handling data and objects Unit - 03

Classes and ObjectsClasses and Objects Classes are the infrastructures Classes are the infrastructures

while objects are runtime utilisation while objects are runtime utilisation of those infrastructuresof those infrastructures

A class has functions and dataA class has functions and data Member functions and data can be Member functions and data can be

of type private, public or protectedof type private, public or protected Default access specifier is Default access specifier is privateprivate Variables cannot be initialised Variables cannot be initialised

during declaration (as you can in during declaration (as you can in Java)Java)

Page 17: Structures, Classes and Objects Handling data and objects Unit - 03

Example: A Simple ClassExample: A Simple Class// demonstrates an object// demonstrates an object

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

class SmallObj class SmallObj // Specify a class name// Specify a class name

{{

private:private:

int m_SomeData; int m_SomeData; // Class data// Class data

public:public:

void SetData(int data) void SetData(int data) // member function to set data// member function to set data

{{

m_SomeData = data;m_SomeData = data;

}}

void ShowData() void ShowData() // member function to display data// member function to display data

{{

cout << “\nData is “ << m_SomeData;cout << “\nData is “ << m_SomeData;

}}

};};

Page 18: Structures, Classes and Objects Handling data and objects Unit - 03

Example: A Simple Class Example: A Simple Class (contd.)(contd.)

void main()void main()

{{

SmallObj s1, s2; SmallObj s1, s2; // defining two objects// defining two objects

s1.SetData(1234); s1.SetData(1234); // calling member function to set data// calling member function to set data

s2.SetData(5677);s2.SetData(5677);

s1.ShowData(); s1.ShowData(); // calling member function to display// calling member function to display

// data// data

s2.ShowData();s2.ShowData();

}}

Page 19: Structures, Classes and Objects Handling data and objects Unit - 03

ConstructorsConstructors

Constructor is a class method with Constructor is a class method with exactly the same name as class exactly the same name as class namename

A constructor may accept A constructor may accept argument(s) but does not return argument(s) but does not return anything, not even anything, not even voidvoid

They are called when an instance of They are called when an instance of the class is createdthe class is created

A default constructor does not A default constructor does not accept any argumentaccept any argument

Page 20: Structures, Classes and Objects Handling data and objects Unit - 03

Constructors (contd.)Constructors (contd.)

If a default constructor is not provided, If a default constructor is not provided, compiler assumes there exists but it does compiler assumes there exists but it does not do anythingnot do anything

Constructors can be overloaded in their Constructors can be overloaded in their argument type and number of argumentsargument type and number of arguments

In constructors, variables can be In constructors, variables can be initialised to a default valueinitialised to a default value

A copy constructor is used when objects A copy constructor is used when objects are copiedare copied

Page 21: Structures, Classes and Objects Handling data and objects Unit - 03

Example: ConstructorsExample: Constructors#include <iostream.h>#include <iostream.h>

class Customer class Customer // Specify a class name// Specify a class name

{{

private:private:

int m_CustomerId; int m_CustomerId; // Class data// Class data

public:public:

Customer() Customer() // no-arg or default constructor // no-arg or default constructor

{{

m_CustomerId = 0; m_CustomerId = 0; // default customer ID// default customer ID

}}

Customer(int newCustomerId) Customer(int newCustomerId) // one-arg constructor // one-arg constructor

{{

m_CustomerId = newCustomerId;m_CustomerId = newCustomerId;

}}

};};

Page 22: Structures, Classes and Objects Handling data and objects Unit - 03

Example: ConstructorsExample: Constructorsvoid main()void main()

{{

Customer ordinaryCustomer; Customer ordinaryCustomer; // creating instance using// creating instance using

// default constructor// default constructor

Customer registeredCustomer(49); Customer registeredCustomer(49); // creating instance// creating instance

// using one-arg constructor// using one-arg constructor

}}

Page 23: Structures, Classes and Objects Handling data and objects Unit - 03

Copy ConstructorCopy Constructor

Copy constructor is used when Copy constructor is used when objects are copiedobjects are copied

Default copy constructor performs Default copy constructor performs shallow copyshallow copy

Explicit copy constructor can be Explicit copy constructor can be provided to perform deep copyprovided to perform deep copy

Page 24: Structures, Classes and Objects Handling data and objects Unit - 03

Shallow and Deep CopyShallow and Deep Copy

m_pAddressm_pAddress

name : e1name : e1

City : LHRCity : LHRState : PunjabState : PunjabCountry : PKCountry : PK

AddressAddress

m_pAddressm_pAddress

name : e1name : e1

City : LHRCity : LHRState : PunjabState : PunjabCountry : PKCountry : PK

AddressAddress

m_pAddressm_pAddress

name : e1name : e1

City : LHRCity : LHRState : PunjabState : PunjabCountry : PKCountry : PK

AddressAddress

m_pAddressm_pAddress

name : e2name : e2

City : LHRCity : LHRState : PunjabState : PunjabCountry : PKCountry : PK

AddressAddress

m_pAddressm_pAddress

name : e2name : e2

Initially Shallow Copy Deep Copy

EmployeeEmployee EmployeeEmployee

EmployeeEmployee

EmployeeEmployee

EmployeeEmployee

Page 25: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Copy Example: Copy ConstructorConstructor

struct SAddressstruct SAddress

{{

char* city;char* city;

char* state;char* state;

char* country;char* country;

SAddress() SAddress()

{{

city = "";city = "";

state = "";state = "";

country = "";country = "";

}}

void DisplayAddress()void DisplayAddress()

{{

cout << city << ", " << state << ", " << country cout << city << ", " << state << ", " << country << endl; << endl;

}}

};};

Page 26: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Copy Constructor Example: Copy Constructor (contd.)(contd.)

class Employeeclass Employee

{{

private:private:

SAddress* m_pAddress;SAddress* m_pAddress;

char* m_Name;char* m_Name;

public:public:

Employee()Employee()

{{

m_pAddress = 0;m_pAddress = 0;

}}

~Employee()~Employee()

{{

delete m_pAddress;delete m_pAddress;

}}

Page 27: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Copy Constructor Example: Copy Constructor (contd.)(contd.) void SetAddress(char* city, char* state, void SetAddress(char* city, char* state,

char* country)char* country)

{{

m_pAddress = new SAddress();m_pAddress = new SAddress();

m_pAddress->city = city;m_pAddress->city = city;

m_pAddress->state = state;m_pAddress->state = state;

m_pAddress->country = country;m_pAddress->country = country;

}}

SAddress* GetAddress()SAddress* GetAddress()

{{

return m_pAddress; return m_pAddress;

}}

void SetName(char* name)void SetName(char* name)

{ {

m_Name = name; m_Name = name;

} }

Page 28: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Copy Constructor Example: Copy Constructor (contd.)(contd.)

char* GetName()char* GetName()

{ {

return m_Name; return m_Name;

}}

void Display()void Display()

{{

cout << m_Name << " -- ";cout << m_Name << " -- ";

m_pAddress->DisplayAddress();m_pAddress->DisplayAddress();

}}

// this copy constructor performs deep copy// this copy constructor performs deep copy

Employee(Employee& e) Employee(Employee& e)

{{

m_pAddress = new SAddress();m_pAddress = new SAddress();

m_pAddress->city = e.GetAddress()->city;m_pAddress->city = e.GetAddress()->city;

m_pAddress->state = e.GetAddress()->state;m_pAddress->state = e.GetAddress()->state;

m_pAddress->country = e.GetAddress()->country;m_pAddress->country = e.GetAddress()->country;

}}

};};

Page 29: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Copy Constructor Example: Copy Constructor (contd.)(contd.)

void main() void main()

{{

Employee e1;Employee e1; // no-arg constructor is called// no-arg constructor is called

e1.SetName("E1");e1.SetName("E1");

e1.SetAddress("LHR", "Punjab", "PK");e1.SetAddress("LHR", "Punjab", "PK");

e1.Display();e1.Display();

Employee e2 = e1;Employee e2 = e1; // copy constructor is called// copy constructor is called

e2.SetName("E2");e2.SetName("E2");

e2.GetAddress()->city = ”ISB";e2.GetAddress()->city = ”ISB"; // change city for e2// change city for e2

e1.Display();e1.Display();

e2.Display();e2.Display();

}}

Page 30: Structures, Classes and Objects Handling data and objects Unit - 03

DestructorsDestructors

Called when an instance of the class is Called when an instance of the class is destroyeddestroyed

Destructor is a class method starting Destructor is a class method starting with tilde (with tilde (~)~) and have exactly the and have exactly the same name as class namesame name as class name

Destructors are used to release Destructors are used to release resources held by the instance (object)resources held by the instance (object)

Destructor does not accept any Destructor does not accept any argumentargument

Page 31: Structures, Classes and Objects Handling data and objects Unit - 03

Destructors (contd.)Destructors (contd.)

Destructor does not return anything, Destructor does not return anything, not even not even voidvoid

Destructors can not be overloadedDestructors can not be overloaded Memory allocated by the instance is Memory allocated by the instance is

released after calling the destructorreleased after calling the destructor Automatically called when the object Automatically called when the object

goes out of scopegoes out of scope

Page 32: Structures, Classes and Objects Handling data and objects Unit - 03

Example: DestructorsExample: Destructors#include <fstream.h>#include <fstream.h>

class MyFileHandlerclass MyFileHandler

{{

private: private:

ofstream m_file;ofstream m_file;

public:public:

MyFileHandler()MyFileHandler()

{ {

m_file.open(“myFile.txt”, ios::binary); m_file.open(“myFile.txt”, ios::binary);

}}

~MyFileHandler()~MyFileHandler()

{{

m_file.close; m_file.close;

}}

Page 33: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Destructors Example: Destructors (contd.)(contd.)

void WriteToFile(int buff[1000])void WriteToFile(int buff[1000])

{{

m_file.write((char*)buff, 1000*sizeof(int));m_file.write((char*)buff, 1000*sizeof(int));

}}

};};

void main()void main()

{{

int myData[1000];int myData[1000];

MyFileHandler myFileHandler;MyFileHandler myFileHandler;

for(int j=0; j < 1000; j++)for(int j=0; j < 1000; j++)

{{

myData[j] = j;myData[j] = j;

}}

myFilehandler.WriteToFile(myData);myFilehandler.WriteToFile(myData);

}}

// as myFileHandler goes out of scope, destructor is called// as myFileHandler goes out of scope, destructor is called

// and the file is closed// and the file is closed

Page 34: Structures, Classes and Objects Handling data and objects Unit - 03

Member FunctionsMember Functions

Member functions are methods of a class, Member functions are methods of a class, could be:could be: private, private, protected or protected or publicpublic

Can be declared and defined together or Can be declared and defined together or separatelyseparately

Inline function’s code is expanded where Inline function’s code is expanded where it is called and differ in normal function it is called and differ in normal function calling mechanismcalling mechanism

Page 35: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Member Example: Member FunctionsFunctions

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

class Employee class Employee // Specify a class// Specify a class

{{

private:private:

int m_EmployeeId; int m_EmployeeId; // Class data// Class data

int m_EmployeeAge;int m_EmployeeAge;

protected:protected:

// implicit inline function // implicit inline function

void ShowAge() void ShowAge() // Member function to show// Member function to show

{ { // Employee age// Employee age

cout << “\nAge is “ << m_EmployeeAge;cout << “\nAge is “ << m_EmployeeAge;

}}

Page 36: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Member Functions Example: Member Functions (contd.)(contd.)

public:public:

void SetId(int id) void SetId(int id) // Member function to set id// Member function to set id

{{

m_EmployeeId = id;m_EmployeeId = id;

}}

void ShowId(); void ShowId(); // Declaration only// Declaration only

void SetAge(int age); void SetAge(int age); // Declaration only// Declaration only

};};

void Employee::ShowId() void Employee::ShowId()

{{

cout << “\nId is “ << m_EmployeeId;cout << “\nId is “ << m_EmployeeId;

}}

// explicit inline function// explicit inline function

inline void Employee::SetAge(int age) inline void Employee::SetAge(int age)

{{

m_EmployeeAge = age;m_EmployeeAge = age;

}}

Page 37: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Member Functions Example: Member Functions (contd.)(contd.)

void main()void main()

{{

Employee manager, worker; Employee manager, worker; // defining two objects// defining two objects

manager.SetId(1001); manager.SetId(1001); // calling member function to// calling member function to

// set Id// set Id

worker.SetId(5001); worker.SetId(5001); // calling member function to// calling member function to

// set Id // set Id

manager.SetAge(45); manager.SetAge(45); // calling member function to set// calling member function to set

// manger’s age// manger’s age

wroker.SetAge(45); wroker.SetAge(45); // calling member function to set// calling member function to set

// worker’s age// worker’s age

}}

Page 38: Structures, Classes and Objects Handling data and objects Unit - 03

Static DataStatic Data

Static data could be any typeStatic data could be any type Also called class dataAlso called class data Lifetime is the entire programLifetime is the entire program Shared among all objects of the same Shared among all objects of the same

class class Static data members are accessed using Static data members are accessed using

class name and class name and :::: operator operator In C++ static data is declared inside the In C++ static data is declared inside the

class and defined outside the classclass and defined outside the class

Page 39: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Static DataExample: Static Dataclass Counter class Counter // Specify a class// Specify a class

{{

private:private:

int m_Count; int m_Count; // class data// class data

public:public:

void IncrementCount()void IncrementCount()

{{

m_Count++; m_Count++;

}}

int GetTotalCount()int GetTotalCount()

{{

return m_Count;return m_Count;

}}

Counter()Counter()

{{

m_Count = 0;m_Count = 0;

}}

}; };

Page 40: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Static DataExample: Static Data (contd.)(contd.)

class Student class Student

{{

private:private:

int m_StudentId; int m_StudentId; // class data// class data

int m_StudentClass;int m_StudentClass;

static Counter sm_Counter; static Counter sm_Counter; // static counter to hold// static counter to hold // count for all students// count for all students

public:public:

void AddStudent(int id ,int studentClass) void AddStudent(int id ,int studentClass)

{ {

m_StudentId = id;m_StudentId = id;

m_StudentClass= studentClass;m_StudentClass= studentClass;

sm_Counter.IncrementCount(); sm_Counter.IncrementCount(); // increment count// increment count

}}

int GetStudentsCount() int GetStudentsCount() // getting class id// getting class id

{{

return sm_Counter.GetTotalCount();return sm_Counter.GetTotalCount();

}}

Page 41: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Static DataExample: Static Data (contd.)(contd.)

};};

Counter Student::sm_Counter; Counter Student::sm_Counter; // if we don’t write this line// if we don’t write this line // compiler will give error// compiler will give error

void main()void main()

{{

Student newStudent;Student newStudent;

Student oldStudent;Student oldStudent;

newStudent.AddStudent(100,10);newStudent.AddStudent(100,10);

oldStudent.AddStudent(23,10);oldStudent.AddStudent(23,10);

cout << “\nTotal = “ << oldStudent.GetStudentsCount();cout << “\nTotal = “ << oldStudent.GetStudentsCount();

} }

Page 42: Structures, Classes and Objects Handling data and objects Unit - 03

Difference Between Structures and Difference Between Structures and ClassesClasses

The default access specifier in class The default access specifier in class is is privateprivate, whereas in structure it is , whereas in structure it is publicpublic

Structures are inherited as Structures are inherited as publicpublic by defaultby default

Classes are inherited as Classes are inherited as privateprivate by by defaultdefault

Page 43: Structures, Classes and Objects Handling data and objects Unit - 03

ReferencesReferences

Available only in C++, not in CAvailable only in C++, not in C One way to pass parameters to function is One way to pass parameters to function is

by referenceby reference The variable passed by reference, if The variable passed by reference, if

altered, changes the actual variable valuealtered, changes the actual variable value & & is used to denote a reference, e.g. &p is used to denote a reference, e.g. &p

(where p is any data type)(where p is any data type) References could be constant, called References could be constant, called

constant referencesconstant references, e.g. const &p, e.g. const &p

Page 44: Structures, Classes and Objects Handling data and objects Unit - 03

Example: ReferencesExample: References// Passing by reference example// Passing by reference example

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

void main()void main()

{{

void IntFrac(const float&, float&, float&);void IntFrac(const float&, float&, float&);

float number,intPart,fracPart;float number,intPart,fracPart;

dodo

{{

cout << “\nEnter a real number:”;cout << “\nEnter a real number:”;

cin >> number;cin >> number;

Intfrac(number,intPart,fracPart);Intfrac(number,intPart,fracPart);

cout << “Integer part is “ << intPartcout << “Integer part is “ << intPart

<< “, fraction part is “ << fracPart;<< “, fraction part is “ << fracPart;

}while (number != 0)}while (number != 0)

}}

Page 45: Structures, Classes and Objects Handling data and objects Unit - 03

Example: References Example: References (contd.)(contd.)

//IntFrac()//IntFrac()

// finds integer and fractional part of the real number// finds integer and fractional part of the real number

void IntFrac(const float& n, float& intp, float& fracp)void IntFrac(const float& n, float& intp, float& fracp)

{{

intp = float(long(n));intp = float(long(n));

fracp = n - intp;fracp = n - intp;

// n can not be changed inside the function as it is // n can not be changed inside the function as it is

// constant reference// constant reference

}}

Page 46: Structures, Classes and Objects Handling data and objects Unit - 03

Friend Classes and Friend Classes and FunctionsFunctions

There are two types of friend modifiers:There are two types of friend modifiers: Class LevelClass Level Function LevelFunction Level

A friend function can access the private A friend function can access the private data of that classdata of that class

A friend function does not belong to a A friend function does not belong to a class, and class, and

Its definition occurs outside the class Its definition occurs outside the class without specifying the class namewithout specifying the class name

Page 47: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Friend Function / Example: Friend Function / ClassClass

// friend function example// friend function example

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

class Beta;class Beta; // forward declaration of class Beta// forward declaration of class Beta

class Alphaclass Alpha

{{

private:private:

int m_Data; int m_Data; // class private data// class private data

public;public;

Alpha()Alpha()

{ {

m_Data = 3; m_Data = 3;

} // assigning class data} // assigning class data

friend int FriFunc(Alpha,Beta); friend int FriFunc(Alpha,Beta); // declaring friend// declaring friend

// function// function

friend Beta; friend Beta; // Beta is friend of// Beta is friend of

// Alpha// Alpha

};};

Page 48: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Friend Function / Class Example: Friend Function / Class (contd.)(contd.)

class Betaclass Beta

{{

private private

int m_Data; int m_Data; // class private data// class private data

public:public:

Beta()Beta()

{{

m_Data = 7;m_Data = 7;

} } // assigning data// assigning data

void ChangeAlpha(Alpha& a);void ChangeAlpha(Alpha& a);

friend int FriFunc(Alpha,Beta); friend int FriFunc(Alpha,Beta); // declaraing friend// declaraing friend

}; }; // function// function

int FriFunc(Alpha a, Beta b)int FriFunc(Alpha a, Beta b) // friend function// friend function

{{

return (a.m_Data + b.m_Data); return (a.m_Data + b.m_Data);

}}

Page 49: Structures, Classes and Objects Handling data and objects Unit - 03

Example: Friend Function / Class Example: Friend Function / Class (contd.)(contd.)

void Beta::ChangeAlpha(Alpha& a)void Beta::ChangeAlpha(Alpha& a)

{{

a.m_Data = 100;a.m_Data = 100; // change Alpha’s private // change Alpha’s private datadata // as Beta is a friend of // as Beta is a friend of AlphaAlpha

}}

void main()void main()

{{

Alpha aa;Alpha aa; // define aa// define aa

Beta bb;Beta bb; // define bb// define bb

cout << FriFunc(aa,bb);cout << FriFunc(aa,bb); // calling friend function// calling friend function

bb.ChangeAlpha(aa);bb.ChangeAlpha(aa); // change Alpha’s private data// change Alpha’s private data // through bb// through bb

cout << FriFunc(aa,bb);cout << FriFunc(aa,bb); // calling friend function// calling friend function

}}

Page 50: Structures, Classes and Objects Handling data and objects Unit - 03

Unit SummaryUnit Summary

In this unit you have covered …In this unit you have covered … StructuresStructures ClassesClasses Static data and member functionsStatic data and member functions ReferencesReferences Friend functions and classesFriend functions and classes