You are on page 1of 81

Classes and Objects

Faculty: Imran Fareed Nizami


imran.farid@bui.edu.pk
Difference between Structures and Classes
• Classes and Structures are very similar
• Structures are usually used to group data items together.
• Classes are usually used to group data items and member functions.
• Differences between Class and Struct
• Class
– Passed by reference
– Can create a subclass that will inherit parent's properties and methods
– A class has all members private by default
– Allow to perform cleanup (garbage collector) before object is deallocated
• Struct
– Passed by copy
– Structure does not support inheritance
– In a struct members are public by default
– Structures can not be garbage collector so no efficient memory management

Functions
Object Oriented Programming
• Object
– Collection of Data and Functions
– May represent a person, thing or place in real world

• In OOP, data and all possible functions on data are


grouped together.
• Object oriented programs are easier to learn and modify.

4
Core concept of OOP

• Combining data and


functions together is the
core idea behind OOP.
What is an object?
An object is an instance of a Class

OBJECT
set of methods
Operations (member functions)

Data Data members


(values of private/protected/public
data members)

6
Features of OOP
• Classes
– Designed for creating objects.
– All properties and functions of an object are specified in classes
• Real-world Modeling
– In real world, things have properties and working capability
– Similarly, objects have data and functions
– Data represent properties and functions represent working of
objects

7
Features of OOP (cont..)
• Reusability
– Inheritance is a technique that allows a programmer to use the code
of existing program to create new program.
• Information Hiding
– OOP allows the programmer to hide important data from the user. It
is performed by encapsulation.
• Polymorphism
– Ability of an object to behave in multiple ways

8
Objects
– An object represents an entity in the real world such as person, thing or
concept etc.
– An object is identified by its name
– An object consists or the following two things:
– Properties: Characteristics of an object
– Functions: Actions that can be performed by an object
• Example:
– Properties of Person Object are: Name, Age, Weight
– Properties of Car Object are: Color, Price, Model
• Example:
– Functions of Car Object are:
– Start
– Stop/Reverse
9
Class
• A collection of objects with same properties and function is known as class
• A Class is used to define the characteristics of the objects.
• It is used as a model for creating different objects of same type

• For Example, a class Person can be used to define the characteristics and
functions of a person. It can be used to create many objects of type Person
such as Ali, Usman, Abdullah etc.

• All objects of Person class will have same characteristics and functions
• Each object of class is known as an instance of its class.
• Ali, Usman and Abdullah are three instances of a class Person.
10
Defining a class
Components of a Class
• The data variables are called “data members”
• The functions of the class are called member functions
• Usually data items are set as private
• Member functions are set as public
• Hence, member functions can access data items to change their values.
Data items of a Class
• Can be any data type.
• They are declared private by default
• The private data members can only be accessed by member functions

Functions
Member Functions of a Class

• Used to
– access the values of the data members
– perform operations on the data members
• Are declared inside the class body
• Their definition can be placed inside the class body, or outside
the class body
• Can access both public and private members of the class
• Can be referred to using dot or arrow member access operator

14
Define a Class Type

Header class Rectangle


class class_name {
{ private:
permission_label:
int width;
member;
Body permission_label:
int length;
member; public:
... void set(int w, int l);
}; int area();
};
15
Declaring Class Objects
foo f1, f2;
– This process is called instantiating.
– An instance of a class foo is created.

Calling member functions of the class


– f1.memfunc(10);
– f2.memfunc(25);
• The dot operator is also called the class member access operator.
Classes & Objects
Objects: Instance of a class
class Rectangle
{
Rectangle r1;
private: Rectangle r2;
int width; Rectangle r3;

……
int length;
public:
void set(int w, int l);
int area(); int a;
};
17
Declaration of an Object

class Rectangle main()


{ {
Rectangle r1;
private:
Rectangle r2;
int width;
int length; r1.set(5, 8);
cout<<r1.area()<<endl;
public:
void set(int w, int l); r2.set(8,10);
cout<<r2.area()<<endl;
int area();
}
};
18
Declaration of an Object
r1 is statically allocated
class Rectangle
{ main()
{
private:
Rectangle r1;
int width;
r1.set(5, 8);
int length; }
public:
void set(int w, int l); r1
width = 5
int area(); length = 8

};
19
A Simple Class
#include <iostream> int main()
using namespace std;
{
class smallobj //define a class
{ smallobj s1, s2;
private: s1.setdata(1066);
int somedata; //class data
s2.setdata(1776);
public:
void setdata(int d) //member function to set data s1.showdata();
{ somedata = d; } s2.showdata();
void showdata() //member function to display data return 0;
{ cout << “Data is “ << somedata << endl; }
}
};
• The first member
function sets the value
of the data items and
the second function
displays their values.
• Each object is called an
instance of the class.
Define a Member Function outside the Class
• It is a way of specifying what class something is associated with. In this
situation, Distance::add_dist() means “the add_dist() member function of the Distance
class.”

Functions
Define a Member Function outside the
Class
class Rectangle
{
private:
int width, length;
class name
public:
void set (int w, int l);
int area() {return width*length; } member function name
};

void Rectangle :: set (int w, int l)


{
r1.set(5,8);
width = w;
rp->set(8,10); length = l;
scope operator
}
23
Another Example
#include <iostream.h> // member function definitions

class circle void circle::store(double r)


{
{ radius = r;
private: }
double radius;
double circle::area(void)
{
public: return 3.14*radius*radius;
void store(double); }
double area(void);
void display(void); void circle::display(void)
{
cout << “r = “ << radius << endl;
}; }

int main(void) {
circle c; // an object of circle class
c.store(5.0);
cout << "The area of circle c is " << c.area() << endl;
c.display(); 24
}
Class Exercise
• Make a class named part
• Declare data members as
– Modelnumber
– Partnumber
– Cost
• Declare members functions as
– Setpart (return type is void, input arguments are 3 data members to be set)
– Showpart (return type is void, input arguments are void)
Example

#include <iostream> void showdist()


using namespace std; { cout << feet << “\’-” << inches << ‘\”’; }
class Distance };
{ int main()
private: {
int feet;
Distance dist1, dist2;
float inches;
dist1.setdist(11, 6.25);
public:
dist2.getdist();
void setdist(int ft, float in)
{ feet = ft; inches = in; } cout << “\ndist1 = “; dist1.showdist();
void getdist() cout << “\ndist2 = “; dist2.showdist();
{ cout << endl;
cout << “\nEnter feet: “; cin >> feet; return 0;
cout << “Enter inches: “; cin >> inches; }
}
Object Initialization
1. By Assignment
#include <iostream.h>
• Only work for public data
class circle members
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment

}
28
Object Initialization
#include <iostream.h>
class circle
{ 2. By Public Member Functions
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};
int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor 29
}
Constructor
• Automatic initialization is carried out using a special member function
called a constructor.
• A constructor is a member function that is executed automatically
whenever an object is created.
• A constructor is a member function having the same name as the class
• No return type is used for constructors.
• One of the most common tasks a constructor carries out is initializing
data members.
Definition of a constructor

counter() counter() : count(0)


{ count = 0; } {}

counter() : m1(7), m2(33), m2(4)


{}
Example constructor
#include <iostream> int main()
using namespace std; {
class Counter Counter c1, c2; //define and initialize
{ cout << “\nc1=” << c1.get_count(); //display
private:
cout << “\nc2=” << c2.get_count();
c1.inc_count(); //increment c1
unsigned int count; //count
c2.inc_count(); //increment c2
public:
c2.inc_count(); //increment c2
Counter() : count(0) //constructor
cout << “\nc1=” << c1.get_count(); //display again
{cout << “I’m the constructor\n”; } cout << “\nc2=” << c2.get_count();
void inc_count() //increment count Chapter 6
{ count++; } 228
int get_count() //return count cout << endl;
{ return count; } return 0;
}; }
Overloaded Constructors
Distance(int ft, float in) : feet(ft), inches(in)
{}

And

Distance() : feet(0), inches(0.0) //default constructor


{ } //no function body, doesn’t do anything

Functions
Overloaded constructors calling
• Distance length; // calls first constructor
• Distance width(11, 6.0); // calls second constructor

Functions
Objects as function arguments
• Constructor overloading • Defining member functions outside the class
private: and Objects as function arguments
int feet;
float inches; void add_dist( Distance, Distance );
public: //prototype declared inside the class
Distance() : feet(0), inches(0.0)
{} //function definition outside the class
Distance(int ft, float in) : feet(ft), void Distance::add_dist(Distance d2, Distance d3)
inches(in){ } { inches = d2.inches + d3.inches;
feet = 0;
• Declaring the Object if(inches >= 12.0)
– Distance width; { inches -= 12.0;
– Distance width(5, 6.25); feet++;
}
feet += d2.feet + d3.feet; //add the feet
}
– (::) scope resolution operator.

Functions
Object Initialization
3. By Constructor
class Rectangle
{
private: • Default constructor
int width; • Copy constructor
int length;
• Constructor with parameters
public:
Rectangle();
Rectangle(const Rectangle &r); They are publicly accessible
Rectangle(int w, int l); Have the same name as the class
void set(int w, int l); There is no return type
int area(); Are used to initialize class data
} members
They have different signatures
36
Object Initialization
When a class is declared with no constructors,
the compiler automatically assumes default
class Rectangle constructor and copy constructor for it.
{
• Default constructor
private:
int width;
Rectangle :: Rectangle() { };
int length;
public:
• Copy constructor
void set(int w, int l);
int area(); Rectangle :: Rectangle (const
Rectangle & r)
}; {
width = r.width; length = r.length;
}; 37
The Default Copy Constructor
#include <iostream> void showdist() //display distance
using namespace std; { cout << feet << “\’-” << inches << ‘\”’; }
class Distance //English Distance class };
{ private:
int feet; int main()
float inches; { Distance dist1(11, 6.25); //two-arg constructor
public: Distance dist2(dist1); //one-arg constructor
Distance() : feet(0), inches(0.0) Distance dist3 = dist1; //also one-arg constructor
{} cout << “\ndist1 = “; dist1.showdist();
Distance(int ft, float in) : feet(ft), inches(in) cout << “\ndist2 = “; dist2.showdist();
{}
cout << “\ndist3 = “; dist3.showdist();
cout << endl; Declare two objects of type
void getdist() //get length from user
return 0; Distance, dist2 and dist3,
{
} initializing both to the value
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches; of dist1.
}
Functions
Object Initialization
• Initialize with default constructor

class Rectangle
Rectangle r1;
{
Rectangle *r3 = new Rectangle();
private:
int width;
• Initialize with copy constructor
int length;
public: Rectangle r4;
void set(int w, int l); r4.set(60,80);
int area(); Rectangle r5 = r4;
} Rectangle r6(r4);
Rectangle *r7 = new Rectangle(r4);
39
Object Initialization

class Rectangle If any constructor with any number


of parameters is declared, no default
{
constructor will exist, unless you
private: define it.
int width;
int length;
Rectangle r4; // error
public:
Rectangle(int w, int l)
• Initialize with constructor
{width =w; length=l;}
void set(int w, int l);
Rectangle r5(60,80);
int area();
Rectangle *r6 = new Rectangle(60,80);
}

40
Object Initialization
Write your own constructors
class Rectangle
{ Rectangle :: Rectangle()
private: {
int width; width = 20;
length = 50;
int length;
};
public:
Rectangle();
Rectangle(int w, int l); Rectangle *r7 = new Rectangle();
void set(int w, int l);
int area(); r7
6000
} 5000
5000
???
width = 20
length = 50
41
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.
#include <iostream>
using namespace std;
class Demo
{
private: int a;
public:
void set(int x)
{
a = x;
}
void sum(Demo ob1, Demo ob2)
{
a = ob1.a + ob2.a;
}
void print()
{
cout<<"Value of A : "<<a<<endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;

//assigning values to the data member of objects


d1.set(10);
d2.set(20);

//passing object d1 and d2


d3.sum(d1,d2);

//printing the values


d1.print();
d2.print();
d3.print();

return 0;
}
Objects as Function Arguments
if(inches >= 12.0) //if total exceeds 12.0,
#include <iostream> void getdist()
{ //then decrease inches
{ inches -= 12.0; //by 12.0 and
using namespace std; cout << “\nEnter feet: “; cin >> feet; feet++; //increase feet
class Distance cout << “Enter inches: “; cin >> inches; } //by 1
{ } feet += d2.feet + d3.feet; //add the feet
private: void showdist() //display distance }
{ cout << feet << “\’-” << inches << ‘\”’; } int main()
int feet; {
void add_dist( Distance, Distance );
float inches; //declaration Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25);
public: //constructor (no args) };
dist1.getdist(); //get dist1 from user
Distance() : feet(0), inches(0.0) void Distance::add_dist(Distance d2, dist3.add_dist(dist1, dist2);
Distance d3)
{} cout << “\ndist1 = “; dist1.showdist();
{ cout << “\ndist2 = “; dist2.showdist();
//constructor (two args) inches = d2.inches + d3.inches; //add the cout << “\ndist3 = “; dist3.showdist();
Distance(int ft, float in) : feet(ft), inches cout << endl;
inches(in) feet = 0; //(for possible carry) return 0;
{} }

Functions
#include <iostream> void Distance::add_dist(Distance d2, Distance d3)
using namespace std; { inches = d2.inches + d3.inches; //add the inches
class Distance feet = 0; //(for possible carry)
{ private: if(inches >= 12.0) //if total exceeds 12.0,
int feet; { inches -= 12.0; //by 12.0 and
float inches; feet++; //increase feet
public: //constructor (no args) } //by 1
Distance() : feet(0), inches(0.0) feet += d2.feet + d3.feet; //add the feet
{ } }
Distance(int ft, float in) : feet(ft), inches(in) //constructor (two args) int main()
{} { Distance dist1, dist3; //define two lengths
void getdist() //get length from user Distance dist2(11, 6.25); //define and initialize dist2
{ cout << “\nEnter feet: “; cin >> feet; dist1.getdist(); //get dist1 from user
cout << “Enter inches: “; cin >> inches; dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2
} cout << “\ndist1 = “; dist1.showdist();
Enter feet: 17
void showdist() //display distance cout << “\ndist2 = “; dist2.showdist();
Enter inches: 5.75
{ cout << feet << “\’-” << inches << ‘\”’; } cout << “\ndist3 = “; dist3.showdist(); dist1 = 17’-5.75”
void add_dist( Distance, Distance ); //declaration cout << endl; dist2 = 11’-6.25”
}; return 0; dist3 = 29’-0”
}
Functions
Functions
• Since add_dist() is a member function of the • In the following statement, what objects can
Distance class add_dist() access?
– It can access the private data in any object of class – dist3.add_dist(dist1, dist2);
Distance – Besides dist3, the object for which it was called, it
– Using dist1.inches and dist2.feet. can also access dist1 and dist2, because they are
• A member function is always given access to supplied as arguments.
– The object for which it was called: the object • void add_dist( Distance, Distance );
connected to it with the dot operator. – Notice that the result is not returned by the
– It may be able to access other objects as well. function. The return type of add_dist() is void.
– The result is stored automatically in the dist3
object.
• Every call to a member function is associated
with a particular object
• The function has direct access to all the
members, whether private or public, of that
object.

Functions
How to return an object from the function?
Returning Objects from Functions
Distance Distance::add_dist(Distance d2)
#include <iostream>
{ Distance temp;
using namespace std;
temp.inches = inches + d2.inches;
class Distance
if(temp.inches >= 12.0)
{ private:
int feet; { temp.inches -= 12.0;
float inches; temp.feet = 1;
public: }
Distance() : feet(0), inches(0.0) {} temp.feet += feet + d2.feet;
Distance(int ft, float in) : feet(ft), inches(in) { } return temp;
void getdist() }
{ cout << “\nEnter feet: “; cin >> feet; int main()
cout << “Enter inches: “; cin >> inches; { Distance dist1, dist3;
} Distance dist2(11, 6.25);
void showdist() dist1.getdist();
{ cout << feet << “\’-” << inches << ‘\”’; dist3 = dist1.add_dist(dist2);
} cout << “\ndist1 = “; dist1.showdist();
Distance add_dist(Distance); //add cout << “\ndist2 = “; dist2.showdist();
}; cout << “\ndist3 = “; dist3.showdist(); cout << endl;
return 0;
}

Functions
Functions
Destructors
• Destructor function is called automatically when an object is destroyed
• Its name is the class name preceded by a ~ (tilde)
• It has no argument

~Foo() //destructor (same name as class with tilde)


{}

• It is used to release dynamically allocated memory and to perform other


"cleanup" activities
• It is executed automatically when the object goes out of scope
Example of destructor
class Foo • Destructors do not have a return
{ value.
private: • Destructors take no input
int data; arguments
public:
Foo() : data(0) { }
~Foo() { }
//destructor (same
name with tilde)
};

Functions
Another example
class Y {
private:
char * string;
int number;
public:
Y(const char*, int);
~Y()
{
delete[] string;
}
};

Functions
class Y { Y::Y(const char* n, int a) {
private: string = strcpy(new char[strlen(n) + 1 ], n);
char * string; number = a;
int number;
cout<<string<<endl;
public:
cout<<a;
Y(const char*, int);
}
~Y() { cout<<"\n I am deleting string bye";
delete[] string; } int main ()
}; {
Y yobj = Y("somestring", 10);
getch();
return 0;
}

Functions
Data Members of Class
• Can be of any type, built-in or user-defined
• non-static data member
– Each class object has its own copy
• static data member
– Acts as a global variable
– One copy per class type, e.g. counter

60
Static data item
• A static data item is useful when all objects of the same class must share
a common item of information.
• It is visible only within the class, but its lifetime is the entire program.
• It continues to exist even if there are no objects of the class.

• Declaration
– static int count;
Static Data Member
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
count
int length;
static int count; r1 r2
public: width width
length length
void set(int w, int l);
int area(); width
r3 length
} 62
Example
#include <iostream> int foo::count = 0;
using namespace std; int main()
class foo { foo f1, f2, f3;
{ private: cout << “count is “ ;
static int count; cout<< f1.getcount() << endl;
public: cout << “count is “ ;
foo() { count++; } cout<< f2.getcount() << endl;
int getcount() cout << “count is “;
{ return count; } cout << f3.getcount() << endl;
}; return 0;
}
// what will be the output
Defining constant
• const keyword
– Constant data member
– Constant object
– Constant member function
– Constant input argument

• Constant data member


– int const a;
• Constant object:
– const Distance football(300, 0);
– We can apply const to objects of classes.
– When an object is declared as const, you can’t modify it.

• Constant member function and input argument:


– Distance Distance::add_dist(const Distance & d2) const
– A constant member function cannot modify the values of data members

Functions
const Member Functions
• A const member function class aClass
guarantees that it will never { private:
modify any of its class’s member int alpha;
data.
public:
void nonFunc()
The non-const function nonFunc() can
modify member data alpha, but the { alpha = 99; }
constant function conFunc() can’t. If it tries void conFunc() const
to, a compiler error results.
{ alpha = 99; } //ERROR: can’t modify
a member
};
Example const
Distance Distance::add_dist(const Distance& d2) const
{ Distance temp; //temporary variable
feet = 0; //ERROR: can’t modify this
d2.feet = 0; //ERROR: can’t modify d2
temp.inches = inches + d2.inches; //add the inches
if(temp.inches >= 12.0) //if total exceeds 12.0,
{ temp.inches -= 12.0; //by 12.0 and
temp.feet = 1; //increase feet The const function cannot modify
} temp.feet += feet + d2.feet; //add the feet by 1 the input parameters as well as
the data members of the object
but it can modify the data
return temp; variables declared within it’s
} scope

Functions
Example of const object
#include <iostream> int main()
using namespace std; {
class Distance //English Distance class const Distance football(300, 0);
{ private:
football.getdist(); //ERROR: football is const
int feet;
float inches;
cout << “football = “;
public: //2-arg constructor football.showdist(); //OK
Distance(int ft, float in) : feet(ft), inches(in){ } cout << endl;
void getdist() //user input; non-const func return 0;
{ cout << “\nEnter feet: “; cin >> feet; }
cout << “Enter inches: “; cin >> inches;
}
void showdist() const //display distance; const func
{ cout << feet << “\’-” << inches << ‘\”’; }
};
Class Definition - Access Control

• Information/data hiding
– To prevent the internal representation
from direct access from outside the class
• Access Specifiers
– public
• may be accessible from anywhere within a
program
– private
• may be accessed only by the member
functions, and friends of this class
– protected
• acts as public for derived classes
• behaves as private for the rest of the
program

70
Class Definition - Access Control
• The default access specifier is private

• The data members are usually private or protected

• A private member function is a helper, may only be


accessed by another member function of the same
class (exception friend function)

71
Access of non member functions to
public member functions continue…

 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.
Friend Functions
 The private members can not be accessed from
outside the class.

 A non-member function can not have an access to


the private data of a class.

 However ……. ?
Friend Functions continue…

 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
 Does not need to be a member of these classes.
 It can be a member function of another class
 To make an outside function friendly to a class, we have to
simply declare this function as a friend of the class.
Friend Functions continue…

 The function declaration class employee


should be preceded by {
the keyword friend.
---
 The function is defined ---
elsewhere in the
program like a normal public :
C++ function. ---
 The function definition ---
does not use either the friend void func (void);
keyword friend or the }
scope operator : :.
Friend Functions continue…

 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.
Friend Functions continue…

Special Characteristics: int frifunc(alpha a, beta b)


 It is not in the scope of the class to which it has //function definition
{
been declared as friend. return( a.data + b.data );
}

 Since it is not in the scope of the class, it cannot be


called using the object of the class.

 It can be invoked like a normal function without the


help of any object.
Friend Functions continue…

Special Characteristics:
int frifunc(alpha a, beta b)
 Unlike member functions, it cannot access the //function definition
member names directly and has to use an object {
return( a.data + b.data );
name and dot membership operator with each }
member name.
 It can be declared either in the public or private part
of a class without affecting its meaning.
 Usually, it has objects as arguments.
Friend Functions continue…

Member function of one class can be friend functions


of another class.
In such cases, they are defined using the scope
resolution operator as:
Friend Functions continue…

class X class Y
{ {
… …
… …
int fun1 ( ); friend int X : : fun1 ( );
… …
}; };
Example of friend function outside the class
#include <iostream>
int frifunc(alpha a, beta b) //function definition
using namespace std;
{
class beta; //needed for frifunc declaration
return( a.data + b.data );
class alpha
}
{ private:
int data;
public:
int main()
alpha() : data(3) { } //no-arg constructor
{
friend int frifunc(alpha, beta); //friend function alpha aa;
}; beta bb;
class beta cout << frifunc(aa, bb) << endl; //call the
{ private:
function
int data;
return 0;
public: }
beta() : data(7) { } //no-arg constructor
friend int frifunc(alpha, beta); //friend function
};
Example of friend function outside the class
class beta; //needed for frifunc declaration
int alpha :: frifunc(alpha a, beta b) //function
class alpha definition
{ private: { return( a.data + b.data );
int data;
}
public:
alpha() : data(3) { } //no-arg constructor
int frifunc(alpha, beta); //member function
int main()
};
{ alpha aa;
class beta beta bb;
{ private: cout << aa.frifunc(aa, bb) << endl;
int data; //call the function
public: getch();
beta() : data(7) { } //no-arg constructor return 0;
friend int alpha :: frifunc(alpha, beta); //friend }
function
};
Friend Class continue…

We can also declare all the class Z


member functions of one {
class as the friend

functions of another class.

friend class X ;
In such cases, the class is
called a friend class. …
};
Example friend Class
#include <iostream> class beta
{ public: //access private alpha data
using namespace std;
void func1(alpha a) { cout << “\ndata1=” << a.data1;}
class alpha
void func2(alpha a) { cout << “\ndata1=” << a.data1;}
{ private:
};
int data1;
int main()
public:
{ alpha a;
alpha() : data1(99) { } //constructor beta b;
friend class beta; //beta is a friend class b.func1(a);
}; b.func2(a);
cout << endl;
return 0;
}
Static Functions
class gamma static void showtotal() //static function
{ private: { cout << “Total is “ << total << endl;
static int total; //total objects of this class }
int id; //ID number of this object void showid() //non-static function
public: { cout << “ID number is “ << id <<
endl;
gamma() //no-argument constructor
}
{ total++; //add another object
};
id = total; //id equals current total
int gamma::total = 0; //definition of total
}
~gamma() //destructor
{ total--;
cout << “Destroying ID number “ <<
id << endl;
}
int main()
{ gamma g1;
gamma::showtotal();
gamma g2, g3;
gamma::showtotal();
g1.showid(); g2.showid(); g3.showid();
cout << “----------end of program----------\n”;
return 0;
}

You might also like