Class and Objects
Dr. Alekha Kumar Mishra
Recall
●
Things having physical or logical existence are
objects
●
A class is a description of a number of similar
objects.
●
An object is said to be an instance of a class
– Alto 800 is an instance of a car
– There can not be an object called Student or
Professor, rather there may be instances of Student
and Professor.
Dr. Alekha Kumar Mishra
Defining class
class ClassName {
access_specifier1:
field11_definition;
field12_definition;
…
access_specifier2:
field21_definition;
field22_definition;
…
};
3
Dr. Alekha Kumar Mishra
Class definition
class FirstClass {
private:
int dataone;
int datatwo;
public:
void setdata(int o, int t) { dataone = o; datatwo = t }
void showdata()
{ cout << “\nData are “ << dataone << datatwo; }
};
Dr. Alekha Kumar Mishra
Class definition(2)
Class name
class FirstClass {
private:
int dataone;
int datatwo;
public:
void setdata(int o, int t) { dataone = o; datatwo = t }
void showdata()
{ cout << “\nData are “ << dataone << datatwo; }
}; Definition ends with
semicolon just like
structure
Dr. Alekha Kumar Mishra
Class definition(3)
Access specifiers or
class FirstClass { visibility of class members
private:
int dataone;
int datatwo;
public:
void setdata(int o, int t) { dataone = o; datatwo = t }
void showdata()
{ cout << “\nData are “ << dataone << datatwo; }
};
Dr. Alekha Kumar Mishra
access specifier
●
public
●
private
●
protected
●
Fields marked as private can only be accessed by functions
that are member of that class (there is an exception)
●
In the FirstClass class, dataone, and datatwo fields are
private fields
●
Fields marked as public can be accessed by anyone
●
The setdata() and showdata() are public these functions can
be called by anyone
Dr. Alekha Kumar Mishra
Class definition(4)
class FirstClass {
private:
Data members
int dataone;
int datatwo;
public:
void setdata(int o, int t) { dataone = o; datatwo = t }
void showdata()
{ cout << “\nData are “ << dataone << datatwo; }
};
Dr. Alekha Kumar Mishra
Restriction on data members
●
A non-static member variable cannot have an
initializer.
●
No member can be an object of the class that is
being declared. (a member can be a pointer to
the class that is being declared.)
●
No member can be declared as auto, extern, or
register.
●
In general, all data members of a class should be
private.
Dr. Alekha Kumar Mishra
Class definition(5)
class FirstClass {
private:
int dataone;
int datatwo;
public:
void setdata(int o, int t) { dataone = o; datatwo = t }
void showdata()
{ cout << “\nData are “ << dataone << datatwo; }
};
Member functions of the class
10
Dr. Alekha Kumar Mishra
Functions Are Public,
Data Is Private
...
Why??
11
Dr. Alekha Kumar Mishra
Answer
●
Data are private to protect them accessing
from any scope outside of its own class
●
Member functions are public to allow
invocation from a scope outside of the class
●
Member fuctions are the ( public ) medium for
performing operations on (private) data
members of the class from outside.
12
Dr. Alekha Kumar Mishra
Member functions
●
Note that the member functions setdata() and
showdata() are definitions contained within the
class definition.
●
Member functions defined inside a class this way
(in a single line) are created as inline functions by
default.
●
It is also possible to declare a function within a
class but define it elsewhere.
●
Functions defined outside the class are not
normally inline.
13
Dr. Alekha Kumar Mishra
Defining objects
●
FirstClass s1, s2; class FirstClass {
– Defines two objects, s1 and private:
s2, of class FirstClass. int dataone;
– Instantiating object s1, s2 of int datatwo;
class FirstClass public:
– Creating objects s1, s2 of void setdata(int o, int t)
class FirstClass
{ dataone = o; datatwo = t }
●
Objects participate in void showdata() {
program operations.
cout << “\nData are “
●
Defining an object is similar << dataone << datatwo; }
to defining a variable of any };
data type int main()
{
●
Objects are sometimes FirstClass s1, s2;
called instance variables of return 0;
}
the class. 14
Dr. Alekha Kumar Mishra
Calling Member Functions
class FirstClass {
●
s1.setdata(10,66);
private:
●
s2.setdata(17,76); int dataone;
●
Member functions can be int datatwo;
accessed only by an object of public:
that class. void setdata(int o, int t)
●
The dot operator (period) { dataone = o; datatwo = t ;}
connects the object name and void showdata() {
the member function. cout << “\nData are “
– Also called the class member << dataone << datatwo; }
access operator.
};
●
Member function calls are int main() {
also called as messages. FirstClass s1, s2;
s1.setdata(10,66);
●
s1.showdata(); can be s2.setdata(17,76);
thought of sending a message s1.showdata();
s2.showdata();
to s1 telling it to show its data return 0;
15
Dr. Alekha Kumar Mishra }
struct vs. class in C++
●
by default all members are public in a struct
●
Whereas, by default all members are private
in a class.
●
In all other respects, structures and classes
are similar to each other.
16
Dr. Alekha Kumar Mishra
Defining member functions
outside the class
●
Member functions that are declared inside a class need to be
defined separately outside class.
●
General form :
– return_type class_name : : function_name(argument declaration) {
function_ body;
}
●
:: indicates that the scope of the function is restricted to the
class_name.
●
Various classes may define members with same name. Their
scope can be resolved using their membership label
●
Member functions can access private data of the class.
●
A member function can call another member function directly
without .(period) operator.
17
Dr. Alekha Kumar Mishra
An example
#include <iostream> void Box::setLength( double len ) {
using namespace std; length = len;
class Box { }
double length; void Box::setBreadth( double bre ) {
double breadth; breadth = bre;
double height; }
void Box::setHeight( double hei ) {
public: height = hei;
// Member functions declaration }
void setLength( double len ); double Box::getVolume(void) {
void setBreadth( double bre ); return length * breadth * height;
void setHeight( double hei ); }
double getVolume(void);
};
18
Dr. Alekha Kumar Mishra
An example(2)
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0;
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0; 19
}
Dr. Alekha Kumar Mishra
Runtime objects
box1
class Box { length
breadth
double length; height
double breadth;
double height;
}; box2
length
breadth
height
Creating objects of Box class
Box box1, box2, box3;
box3
length
breadth
height
20
Dr. Alekha Kumar Mishra
Referring to the fields
by a member function
#include <iostream>
using namespace std;
class Box { int main() {
double length; ...
double breadth; ...
double height;
...
public: volume = Box1.getVolume();
// Member functions declaration
double getVolume(void); volume = Box2.getVolume();
void setLength( double len );
void setBreadth( double bre ); return 0;
void setHeight( double hei ); }
};
●
When getVolume() is called with
double Box::getVolume(void) {
return length * breadth * height;
reference to object Box1, then it
} refers to the member instances of
void Box::setLength( double len ) { Box1
length = len;
} ●
When called with reference to
void Box::setBreadth( double bre ) { object Box2, these fields referes to
breadth = bre;
}
the member copies of Box2
void Box::setHeight( double hei ) { 21
height = hei;
} Kumar Mishra
Dr. Alekha
Accessing data
members by a
int main() { member function
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box box1
double volume = 0.0; length = 6.0
box1
breadth = 7.0
// box 1 specification
Box1.setLength(6.0); height = 5.0
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification box2
Box2.setLength(12.0); length= 12.0
Box2.setBreadth(13.0); box2
breadth = 13.0
Box2.setHeight(10.0); height= 10.0
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
22
Dr. Alekha Kumar Mishra
Types of class member functions
●
Generally we group class methods into three broad
categories:
●
accessors - allow us to access the fields of a class instance
(examples: getLength, getBreadth, getHeight), accessors do
not change the fields of a class instance
●
mutators - allow us to change the fields of a class instance
(examples: setLength, setBreadth), mutators do change the
fields of a class instance
●
manager functions – special kind of functions (constructors,
destructors) that deal with initializing and destroying class
instances
23
Dr. Alekha Kumar Mishra
Types of class member functions
●
Why do we bother with accessors and mutators?
●
Why provide showdata()?? Why not just make the
member field publicly available?
●
By restricting access using accessors and mutators,
we make it possible to change the underlying details
regarding a class without changing how people
interact with the class
●
If users interact using only accessors and mutators,
then we can change things inside a class without
affecting user’s code
24
Dr. Alekha Kumar Mishra
Array of objects
●
It refers to array of variables that are of the type of
some defined class
●
Similar to other arrays, we can use index operator
and dot operator to access individual elements of
array objects
●
Example
– Box box[10]; //array of objects of type Box
– cin >> box[5].width;
– box[2].length = 44.5;
– cout << box[1].length << box[2].length;
25
Dr. Alekha Kumar Mishra
int main() {
Distance dist1, dist2, dist3;
...
#include <iostream>
...
using namespace std;
dist1.getdist();
class Distance {
dist2.getdist();
private:
dist3.add_dist(dist1, dist2);
int feet;
dist3.getdist();
float inches;
...
public:
return 0;
... // implement getdist(), and setdist() member
}
function
void add_dist( Distance, Distance );
};
void Distance::add_dist(Distance d2, Distance d3) {
inches = d2.inches + d3.inches;
feet = 0;
if(inches >= 12.0) {
inches -= 12.0; Objects as
}
feet++; function
}
feet += d2.feet + d3.feet; arguments 26
Dr. Alekha Kumar Mishra
Manager functions
●
Sometimes, however, it is convenient if an object can
initialize itself when it’s first created, without
requiring a separate call to a member function.
●
It would also be better if some predefined tasks that
we need to perform every time we create an object
are done automatically when an object is created.
●
How about triggering some predefined task when an
object is destroyed automatically?
●
The solution is provided by C++ through manager
functions such as constructors and destructors
27
Dr. Alekha Kumar Mishra
constructors
●
Automatic initialization is carried out using a
special member function called a constructor.
●
A constructor is a member function that is
executed automatically (or called automatically)
whenever an object is created.
●
Therefore, it substitutes the task of defining
member function for initialization and explicitly
calling them.
●
The term constructor is sometimes abbreviated
as ctor
28
Dr. Alekha Kumar Mishra
Constructor features
●
Constructor bears the same name as of class
●
Constructors with no arguments is known as the default
constructor
●
Constructor can’t have a return type
●
If no constructor is provided by the programmer then
compiler provides one default constructor
●
They cannot be inherited, though a derived class can call
the base class constructor
●
Cannot be made virtual
●
It should always be declared in public part of the class
structure. (why??)
29
Dr. Alekha Kumar Mishra
Destructors
●
It is a special member function named same as the class and
preceded by a ~ (tilde)
●
Example:
class Time{
… public:
~Time();
}
●
if your class allocates space on the heap, it is useful to
deallocate that space before the object is destroyed
●
It is used to free the state of an object
●
These are called implicitly when an automatic object goes out
of scope. But if an object is initialized using new than it has to
be deleted
●
In very unusual situations does the user need to call a
30
destructor explicitly!
Dr. Alekha Kumar Mishra
Types of constructor
●
Constructors can be overloaded i.e. there may
be more than one constructors for the same
class with several ways of initialization
●
Types
– Default constructor
– Parameterized constuctor
– Copy constructor
31
Dr. Alekha Kumar Mishra
// object represents a counter variable Default
#include <iostream>
using namespace std; constructor
class Counter {
private:
unsigned int count;
public: int main() {
Counter() : count(0) { } Counter c1, c2;
void inc_count() { count++; } cout << “\nc1=” << c1.get_count();
void dec_count() { count--; } cout << “\nc2=” << c2.get_count();
int get_count() { return count; }
}; c1.inc_count(); //increment c1
c2.inc_count(); //increment c2
c2.inc_count(); //increment c2
cout << “\nc1=” << c1.get_count();
cout << “\nc2=” << c2.get_count();
cout << endl;
return 0; 32
}
Dr. Alekha Kumar Mishra
//constructors, adds objects using member function int main() {
#include <iostream> Distance dist1, dist3;
using namespace std; Distance dist2(11, 6.25);
class Distance { dist1.getdist();
private: dist3.add_dist(dist1, dist2);
int feet; cout << "\ndist1 = ";
float inches; dist1.showdist();
Public: cout << "\ndist2 = ";
Distance() : feet(0), inches(0.0) { } dist2.showdist();
Distance(int ft, float in) : feet(ft), inches(in) { } cout << "\ndist3 = ";
void getdist() { dist3.showdist();
cout << “\nEnter feet: “; cin >> feet; cout << endl;
cout << “Enter inches: “; cin >> inches; return 0;
} }
void showdist() { cout << feet << “\’-” << inches << ‘\”’; }
void add_dist( Distance, Distance );
};
void Distance::add_dist(Distance d2, Distance d3) {
inches = d2.inches + d3.inches;
feet = 0;
if(inches >= 12.0) {
inches -= 12.0;
feet++;
Parameterized
}
feet += d2.feet + d3.feet;
constructor 33
}
Dr. Alekha Kumar Mishra
Parameterized constructor :
Special case
●
If a constructor only #include <iostream>
using namespace std;
has one parameter, class X {
there is a third way to int a;
public:
pass an initial value X(int j) { a = j; }
int geta() { return a; }
to that constructor. };
int main(){
X ob = 99; // passes 99 to j
X ob(99);
cout << ob.geta(); // outputs 99
return 0;
}
34
Dr. Alekha Kumar Mishra
A combination constructor
●
Can combine a ctor that requires arguments with the default ctor using default
values:
●
class Box {
...
public:
Box(double w = 0.0, double h = 0.0, double d = 0.0) {
width = w; height = h; depth = d;
}
};
calling:
Box box1; // ctor called with default args
Box box2();; // ctor called with default args
Box box3(5.0); // ???
Box box4(10.0,10.0,10.0);
35
Dr. Alekha Kumar Mishra
#include <iostream>
using namespace std;
class Distance{
Example: int feet;
float inches;
Destructor public:
Distance(void){ cout << "Object created" <<endl; }
~Distance(void){ cout << "Object destroyed" << endl; }
void getdist() {
cout << "\nEnter feet: "; cin >> feet;
cout << "\nEnter inches: "; cin >> inches;
}
void showdist() { cout << feet << "\'-" << inches << '\"'<<endl; }
};
int main(){
Distance *ob1= new Distance();
ob1->getdist();
ob1->showdist();
delete ob1;
Distance *ob2= new Distance();
ob2->getdist();
ob2->showdist();
delete ob2;
return 0; 36
}
Dr. Alekha Kumar Mishra
Array of objects initialization
#include <iostream>
using namespace std;
class Number {
int i;
public:
Number(int j) { i=j; }
int get_i() { return i; }
};
int main() {
Number ob[3] = {1, 2, 3}; //short version of initialization
Number ob[3] = { Number(1), Number(2), Number(3) };
//longer form of initialization
... 37
}
Dr. Alekha Kumar Mishra
Array of objects initialization
●
If an object's constructor requires two or more
arguments, you will have to use the longer
initialization form
●
Example :
class Coordinate2d {
int x;
int y;
public:
Coordinate2d(int j, int k) { x=j; y=k; } // constructor with 2 parameters
...
};
int main() {
Coordinate2d ob[3] = { Coordinate2d (1, 2), Coordinate2d (3, 4),
Coordinate2d (5, 6) };
... 38
}
Dr. Alekha Kumar Mishra
What is the problem with this?
#include <iostream>
using namespace std;
class Number {
int i;
public:
Number(int j) { i=j; }
int get_i() { return i; }
};
int main() {
Number ob[3];
...
}
39
Dr. Alekha Kumar Mishra
Pointers to
#include <iostream>
using namespace std;
objects
class Number {
int i;
public:
Number(int j) { i=j; }
int get_i() { return i; }
};
int main() {
Number ob(88), *p;
p = &ob; // get address of ob
cout << p->get_i();
...
...
Number ob2[3] = {1, 2, 3};
p = ob2; // get start of array
for(i=0; i < 3; i++) {
cout << p->get_i() << "\n";
p++;
}
return 0;
}
40
Dr. Alekha Kumar Mishra
this pointer
●
When a non-static member function is called, automatically
a pointer to the invoking object is passed as an implicit
argument.
●
This pointer is called this
●
Every object has access to its own address through this
pointer
●
The this pointer is implicitly used to refer both the data and
function members of an object
●
It can also be used explicitly;
– Example: (*this).x=5; or this->x=5;
41
Dr. Alekha Kumar Mishra
Example : this pointer
#include <iostream>
using namespace std;
class pwr {
double b;
int e;
double val;
public:
pwr(double base, int exp);
double get_pwr() { return val; }
};
pwr::pwr(double base, int exp) { pwr::pwr(double base, int exp) {
b = base; this->b = base;
e = exp; this->e = exp;
val = 1; this->val = 1;
for( ; exp>0; exp--) val = val * b; for( ; exp>0; exp--)
} this->val = this->val * this->b;
int main(){ }
pwr x(4.0, 2), y(2.5, 1), z(5.7, 0);
cout << x.get_pwr() << " ";
cout << y.get_pwr() << " ";
cout << z.get_pwr() << "\n";
return 0;
} 42
Dr. Alekha Kumar Mishra
Pointers to class members
#include <iostream>
using namespace std;
class Number {
public:
Number (int i) { val=i; }
int val;
int double_val() { return val+val; }
};
int main() {
int Number::*data; // data member pointer
int (Number::*func)(); // function member pointer
Number ob1(1), ob2(2);
data = &Number::val; // get offset of val
func = &Number::double_val; // get offset of double_val()
cout << "Original values: ";
cout << ob1.*data << " " << ob2.*data << "\n";
cout << "Doubled values: ";
cout << (ob1.*func)() << " ";
cout << (ob2.*func)() << "\n";
return 0;
}
43
Dr. Alekha Kumar Mishra
Copy constructor
●
One of the most important forms of an overloaded
constructor
●
A copy constructor can help to prevent problems
occurs when one object is used to initialize another.
●
By default, when one object is used to initialize
another, C++ performs a bitwise copy.
●
That is, an identical copy of the initializing object is
created in the target object.
●
A common case is when an object allocates
memory dynamically when it is created.
44
Dr. Alekha Kumar Mishra
Copy constructor
●
For example,
– assume a class called MyClass that allocates memory
dynamically for each object when it is created, and an
object A of that class.
– If a bitwise copy is performed, then B will be an exact
copy of A.
– This means that B will be using the same piece of
allocated memory that A is using, instead of allocating its
own.
– Clearly, this is not the desired outcome.
– if MyClass includes a destructor that frees the memory,
then the same piece of memory will be freed twice when
A and B are destroyed! 45
Dr. Alekha Kumar Mishra
Copy constructor
●
When a copy constructor exists, the default copy constructor ( bitwise
copy ) is bypassed.
●
The most common general form of a copy constructor is
classname (const classname &o) {
// body of constructor
}
●
It is permissible for a copy constructor to have additional parameters as
long as they have default arguments defined for them.
●
C++ defines three distinct types of initialization in which the value of one
object is given to another.
– When one object explicitly initializes another, such as in a declaration (myclass
x = y;)
– When a copy of an object is made to be passed to a function ( func(y) )
– When a temporary object is generated; most commonly, as a return value. (y =
func(); )
●
The copy constructor applies to these initializations. 46
Dr. Alekha Kumar Mishra
class Distance {
Example:
private:
int feet;
Copy constructor
float inches;
public:
Distance() : feet(0), inches(0.0) { }
Distance(int ft, float in) : feet(ft), inches(in) { }
Distance(const Distance& ob) {
feet = ob.feet; inches = ob.inches;
}
void showdist() {
cout << feet << "\'-" << inches << '\"';
}
};
int main() {
Distance dist1(11, 6.25);
Distance dist2(dist1);
Distance dist3 = dist1;
cout << " \n dist1 = "; dist1.showdist();
cout << " \n dist2 = "; dist2.showdist();
cout << " \n dist3 = "; dist3.showdist();
cout << endl;
return 0;
} 47
Dr. Alekha Kumar Mishra
Example : Copy constructor
class Table{ int main(){
char *name; Table t1;
float size; Table t2=t1;
... Table t3;
Table(float s=15){ t3=t2; //???
name=new char[size=s]; ...
} ...
Table (const Table&); }
};
Table::Table(const Table& t){
name=new char[size=t.size];
strcpy(name,t.name);
}
●
Why copy constructor argument is passed as
const reference?? 48
Dr. Alekha Kumar Mishra
Answer
●
Reference argument to the copy constuctor
avoids recursive call to it, since when an
object is passed by value the same copy
constructor is invoked to create a copied
object.
●
Foremost reason of const specification is to
avoid accidental modification of the object.
Moreover, we can not have non-const
reference to any temporary objects.
49
Dr. Alekha Kumar Mishra
const objects
●
Objects can be made const by using the const
keyword.
●
All const variables must be initialized at time of
creation using constructors
●
Once a const class object has been initialized via
constructor, any attempt to modify the member
variables of the object is disallowed
●
Example
– const Distance obj3;
50
Dr. Alekha Kumar Mishra
const member function
●
const class objects can only call const member functions
●
A const member function is a member function that guarantees it will not
change any class variables or call any non-const member functions.
●
To make a function a const member function, we simply append the const
keyword to the function prototype
●
Any const member function that attempts to change a member variable or
call a non-const member function will cause a compiler error to occur
class Distance {
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0) { }
Distance(int ft, float in) : feet(ft), inches(in) { }
...
void showdist() const {
cout << feet << "\'-" << inches << '\"';
} 51
};
Dr. Alekha Kumar Mishra
Static member of a class
●
Static data member is an attribute that is a part of class, yet
is not a part of an object
●
In otherwords, there is exactly one copy of a static member
instead of one copy per object
●
A Function that needs access to members of a class, yet
does not need to be invoked for a particular object is called
static member function
●
Often used when declaring class constants (since you generally only
need one copy of a constant)
● To make a field static, add the static keyword in front of the field
– can refer to the field like any other field
– static variables are also considered to be global, you can refer to them
without an instance static fields can be initialized
52
Dr. Alekha Kumar Mishra
Static class members
●
Static data members are accessible by both static
and/or non-static member functions
●
Static member functions can only access the static
class members
●
To access a public static class member, simply prefix
the class name and scope resolution operator
●
To access a private static class member, when no
object exists take help of a static member function
otherwise non-static could be used.
53
Dr. Alekha Kumar Mishra
class Employee{
char* Name;
Example
static int count;
public:
char* getName();
static int getCount();
static void incCount();
};
int Employee::count=0;
int Employee::getCount() {return count;}
void Employee::incCount() { count++; }
char* Employee::getName() { return Name; }
main(){
cout<<“no of Employees: “<< Employee::getCount()<<endl;
Employee* e1=new Employee (“Bob”);
e1->incCount();
Employee* e2=new Employee (“John”);
e2->incCount();
cout<<“no of employees: “ <<Employee::getCount(); 54
}
Dr. Alekha Kumar Mishra
class Employee{
char* Name; A complete example
static int count;
public:
main(){
Employee(char*); cout<<“no of Employees: “<<
char* getName(); Employee::getCount()<<endl;
static int getCount();
Employee* e1= new Employee(“Bob”);
~Employee();
Employee* e2=new Employee (“John”);
};
cout<<“no of employees: “ <<
int Employee::count=0; e1->getCount();
int Employee::getCount()
cout<<“Emp1: “<<e1->getName();
{return Count;}
Employee::Employee(char* N){ cout<<“Emp2: “<<e2->getName();
Name=new char[strlen(N)+1]; delete e1;
strcpy(Name,N); cout<<“no of employees: “
++count;
<<e2->getCount();
}
Employee::~Employee(){ delete e2;
delete [] Name; cout<<“no of employees: “ <<
--count; Employee::getCount();
} }
char* Employee::getName(){
return Name; 55
}
Dr. Alekha Kumar Mishra
Friend function
●
There could be a situation where we would like two
classes to share a particular fuction
●
Example
– findarea() can be shared by rectangle and triangle class
– income_tax() function by manager and clerks class
●
C++ allows the common function to be made
friendly with both the classes.
●
The friendly function is allowed to access to the
private data of these classes
56
Dr. Alekha Kumar Mishra
Friend function
●
To make an outside
class XYZ {
function friend of a
class, the declaration ...
public:
of the function friend void frndfun();
included in the class ...
with friend keyword };
57
Dr. Alekha Kumar Mishra
Features of a friend function
●
It is not in the scope of the class to which it
has been declared as friend
●
It can not be called using the object reference
●
It access the members of an object using dot
operator ( like A.x)
●
Usually has objects as argument
●
Often used in operator overloading
58
Dr. Alekha Kumar Mishra
#include <iostream> Member function
using namespace std;
as friend
class Point2D;
class Circle{
int centerX;
int centerY;
int rad; class Point2D{
public:
void show(){ int xco;
cout << "Center : " int yco;
<< centerX << centerY << endl; public:
cout << "Radius : " int getX(void) { return xco; }
<< rad << endl; int getY(void) { return xco; }
} void setPoint(int x,int y)
void setValues(Point2D,int); { xco =x; yco =y; }
}; friend void Circle::setValues(Point2D,int);
};
void Circle::setValues(Point2D p, int r){
centerX = p.xco;
centerY = p.yco;
rad = r; 59
Dr. Alekha Kumar Mishra
}
An example of friend function
Rectangle duplicate (Rectangle rectparam) {
Rectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
// friend functions }
#include <iostream>
using namespace std; int main() {
class Rectangle { Rectangle rect, rectb;
int width, height; rect.set_values (2,3);
public: rectb = duplicate (rect);
void set_values (int, int); cout << rectb.area();
int area () { return 0;
return (width * height); }
}
friend Rectangle duplicate (Rectangle);
};
void Rectangle::set_values (int a, int b)
60
{ width = a; height = b; }
Dr. Alekha Kumar Mishra
Friend class
●
We can also declare all the member functions of one
class as the friend function of another class.
●
Here entire class is a friend class.
class X {
...
friend class Y;
...
};
61
Dr. Alekha Kumar Mishra
// friend class An Example of
#include <iostream>
using namespace std; Friend class
class Square;
class Rectangle { void Rectangle::convert(Square a){
int width, height; width = a.side;
public: height = a.side;
int area() { }
return (width * height); int main(){
} Square sqr;
void convert (Square a); Rectangle rect;
}; sqr.set_side(4);
class Square { rect.convert(sqr);
private: cout << rect.area();
int side; return 0;
public: }
void set_side (int a){
side=a;
}
friend class Rectangle;
62
};
Dr. Alekha Kumar Mishra
End of Class and Object Slides
63
Dr. Alekha Kumar Mishra