0% found this document useful (0 votes)
10 views167 pages

OOP - Lecture 6 Classes

The document discusses object-oriented programming concepts like classes, objects, encapsulation, and access specifiers. It provides examples of defining a Rectangle class with width and length attributes, and functions to display, calculate area, and set/get width and length values. Private member functions and const member functions are also covered. The key points are that classes bundle data and functions together through objects, and access specifiers control access to class members.

Uploaded by

mohsinbhatti053
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)
10 views167 pages

OOP - Lecture 6 Classes

The document discusses object-oriented programming concepts like classes, objects, encapsulation, and access specifiers. It provides examples of defining a Rectangle class with width and length attributes, and functions to display, calculate area, and set/get width and length values. Private member functions and const member functions are also covered. The key points are that classes bundle data and functions together through objects, and access specifiers control access to class members.

Uploaded by

mohsinbhatti053
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/ 167

National University of Computer

and Emerging Sciences

Spring 2022

Hira Naveed
Lecture # 6 Classes
Procedural Programming

• Data is stored in a collection of variables and/or


structures, along with a set of functions that perform
operations on the data

• The data and the functions are separate entities


double width;
double length; Data

displayWidth();
displayLength(); Functions
displayArea();
Limitations of Procedural Programming

• Variables and data structures are passed to the functions


that perform the desired operations

• What if the data types or data structures change? Many


functions must also be changed – Error prone

• As the procedural programs become larger, function


hierarchies become more complex:

• difficult to understand and maintain


• difficult to modify and extend
Object Oriented Programming

• Procedural programming focuses on creating


procedures, object-oriented programming focuses on
creating objects
Encapsulation refers
• An object is a self-contained unit that consists
to the of both
combining of
data and procedures. data and code into a
single object

double width;
Data
double length;
Rectangle
displayWidth();
Object
displayLength(); Functions
displayArea();
Some Examples of Objects

• Attributes:
• on (true/false)
• Behavior
Car
• Switch on • Attributes:
• Switch off
• Gas in tank
• Check if on
Light Bulb • Mileage
• Behavior
• Attributes:
• Accelerate
• balance
• Brake
• Behavior
• Load fuel
• Deposit • Check fuel
• Withdraw
Bank Account • Check balance
Objects Interact with Each Other

Get Loan

Bank Customer

Deduct Zakat Deposit


Withdraw

Bank Account
Object-Oriented Programming
Terminology
• Class: an abstract data-type or a user-defined data type,
similar to a struct (allows bundling of related variables)

• Object: an instance of a class, in the same way that a


variable can be an instance of a struct
Classes and Objects
• A class is like a blueprint and objects are like houses
built from the blueprint
Classes and Objects
• An object is an instance (realization) of a class
• A single class can have multiple instances
Introduction to Classes

• Objects are created from a class


• Format:
class ClassName
{
variable declaration;
methods declaration;
};
Attribute values define
Class Example the state in objects

Functions define the


class Rectangle behavior of objects

{
double width;
Data (attributes)
double length;

displayWidth();
displayLength(); Functions
displayArea();
};
width = 2
length = 5
width = 4
width = 4 length = 3
length = 2
Defining an Instance of a Class

• An object is an instance of a class, to create an object:


ClassName objectName;

Rectangle r;

• Every object has a unique identity, its own state


Access Specifiers

• Used to control access to members (attributes and


methods) of the class

• public: can be called / accessed by functions outside


of the class

• private: can only be called / accessed by functions


that are members of the class
Rule of Thumb:
Class Example Keep data attributes
private and functions public

class Rectangle To protect data from


{ unwanted access and
modification a.k.a data
private: hiding
double width; Private Members

double length;

public:
void displayWidth(); Public Members
void displayLength();
void displayArea();
};
More on Access Specifiers

• Can be listed in any order in a class

• Can appear multiple times in a class

• If not specified, the default is private


Access Specifiers

• A class is similar to struct, but not the same

• Members of a struct are public by default

struct Rectangle
Members of a class
{ are
double width; private by default
double length;
} r1;

cout << r1.width; //legal because width is public


Access Specifiers

• A class is similar to struct, but not the same

• Members of a class are private by default

class Rectangle
{
double width;
double length;
};
Rectangle r1; //class object
cout << r1.width; //ERROR, width is private
Access Specifiers

class Rectangle {
private:
double width; Access any public
members
double length; of the class using the dot
public: operator:
r1.displayArea(
double getWidth(){ )
return width; }
};
Rectangle r1; //class object r1
cout << r1.getWidth(); //works getWidth()
is public
Defining a Member Functions

• Can be defined within the class declaration (in-line


member function) or outside the class (out-of-line
member functions)

class Rectangle {
private:
double width;
double length;
public:
double calcArea() {
return width * length; //inline func
}
};
Defining a Member Functions

• When defining a member function outside a class (out-of-


line function):
• Put prototype in class declaration
• Define function outside using class name and scope
resolution operator (::)
• Combine class name with member function name

returnType ClassName::MemberFunctionName( ){
…………
}
• Different classes can have member functions with the
same name
Defining a Member Functions

class Rectangle {
private:
double width;
double length;
public:
double calcArea(); //prototype
}; //class declaration ends

double Rectangle::calcArea()
{ return width * length; //out-of-line func
}
Defining a Member Functions
Whether member
function is inline or out-
class Rectangle { of-line
private: Access remains the
same as declared in
double width; the class
double length;
public:
double calcArea(); //prototype
}; //class declaration ends

double Rectangle::calcArea()
{ return width * length; }
Private Member Functions
• Private Member Functions:
• Only accessible (callable) from member functions of
the class

• No direct access possible (with object instance of the


class)

• Can be: inline / out-of-line


Private Member Functions

class Rectangle {
private: private member function
(out-of-line)
double width;
double length;
double calcArea();

public:
void displayArea(){ cout<<
calcArea();}
};
double Rectangle::calcArea(){
return length * width;
Using Private Member Functions

• A private member function can only be called


by another member function

• It is used for internal processing by the class,


not for use outside of the class
Private Member Functions

class Rectangle {
private: private member function
(inline)
double width;
double length;
double calcArea(){
return length * width;
}

public:
void displayArea(){ cout<<
calcArea();}
};
Setters and Getters

• Setter (Mutator): a member function that assigns a


value to a class data member

• Getter (Accessor): a function that reads/gets a value


from a class data member.
class Rectangle {
private:
double width;
double length;
public:
void setWidth(double w){ //setter
width = w; }
void setLength(double l){ //setter
length = l; }
double getWidth(){ //getter
return width; }
double getLength(){ //getter
return length; }
}
Code outside the class must use the class's
public member functions to interact with the
object

Constraints can be added in setters to prevent unwanted


values in data members
Using const With Member Functions

• A const member function is read-only, cannot change


the value of any attribute

class Rectangle
{
private:
double width;

public:
void changeWidth() const {
width++; //ERROR }
};
Getters do not change an object's data,
so they should be marked const.
class Rectangle
{
private:
double width;
double length;
public:
void setWidth(double);
void setLength(double);

double getWidth() const


{ return width; }

double getLength() const


{ return length; }

double getArea() const


{ return width * length; }
};
Pointer to an Object

Rectangle myRectangle; //Rectangle object

• Can define a pointer to an object:


Rectangle *rPtr; //Rectangle pointer

• Can access public members via pointer:


rPtr = &myRectangle;
Pointer to an Object

• Can access public members via pointer:


rPtr = &myRectangle;

• Recall you can use * and . OR ->


rPtr->setWidth(12.5);

cout << rPtr->getLength() << endl;


Pointer to an Object

• Can access public members via pointer:


rPtr = &myRectangle;
rPtr->setWidth(12.5);
rectPtr->setLength(4.8);
Pointer to an Object

• Dynamically allocate objects using a pointer

Rectangle *rPtr = new Rectangle;


rPtr->setLength(12.5);
rPtr->setWidth(10.3);

• Deallocate memory and delete object


delete rPtr;
rPtr = NULL;
Reference to Objects
Reference to Objects

• Reference is an alias to an existing object

38
Reference and Pointers to Objects
Separating Specification from
Implementation
• Makes it easier to modify programs

• Header files (.h)


• Contains class definitions and function prototypes

• Source-code files (.cpp)


• Contains member function definitions
1 // Fig. 6.5: time1.h
2 // Declaration of the Time class.
3 // Member functions are defined in time1.cpp
4
5 // prevent multiple inclusions of header file Dot ( . ) replaced with underscore ( _ ) in file name.

6 #ifndef TIME1_H
7 #define TIME1_H
If time1.h (TIME1_H) is not defined (#ifndef)
8 then it is loaded (#define TIME1_H). If TIME1_H
9 // Time abstract data type definition is already defined, then everything up to #endif is
ignored.
10 class Time { This prevents loading a header file multiple times.
11 public:
12 Time(); // constructor
13 void setTime( int, int, int ); // set hour, minute, second
14 void printMilitary(); // print military time format
15 void printStandard(); // print standard time format
16 private:
17 int hour; // 0 - 23
18 int minute; // 0 - 59
19 int second; // 0 - 59
20 };
21
22 #endif
23 // Fig. 6.5: time1.cpp
24 // Member function definitions for Time class.
25 #include <iostream>
26
27 using std::cout;
28 Source file uses #include to load the
29 #include "time1.h" header file
30
31 // Time constructor initializes each data member to zero.
32 // Ensures all Time objects start in a consistent state.
33 Time::Time() { hour = minute = second = 0; }
34
35 // Set a new Time value using military time. Perform validity
36 // checks on the data values. Set invalid values to zero.
37 void Time::setTime( int h, int m, int s )
38 {
39 hour = ( h >= 0 && h < 24 ) ? h : 0;
40 minute = ( m >= 0 && m < 60 ) ? m : 0;
41 second = ( s >= 0 && s < 60 ) ? s : 0; Source file contains
42 } function definitions
43
44 // Print Time in military format
45 void Time::printMilitary()
46 {
47 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
48 << ( minute < 10 ? "0" : "" ) << minute;
49 }
50
51 // Print time in standard format
52 void Time::printStandard()
53 {
54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
55 << ":" << ( minute < 10 ? "0" : "" ) << minute
56 << ":" << ( second < 10 ? "0" : "" ) << second
57 << ( hour < 12 ? " AM" : " PM" );
58 }
Constructors

• Member function that is automatically called


when an object is created

• Purpose is to construct an object

• Constructor function name is class name

• Has no return type

• A class can have multiple constructors


Constructors

class Demo
{
public:
Demo(); // Constructor
};

Demo::Demo() //out-of-line
{
cout << "Welcome to the constructor!\n";
}
Constructors

class Demo
{
public:
Demo(){ //inline function

// Constructor
cout << "Welcome to the constructor!\n";
}
};
Constructors

• Whenever an instance of a class is created, the


constructor is automatically called

Demo dem; //object dem is created

//Prints
Welcome to the constructor!
Constructors
What Constructors Do

• Help in initializing class data members


Employee( ) { id = 0; }

• Allocate memory for dynamic members


Employee() {
char* nameptr = new char[20];
}

• Allocate any needed resources


• Such as to open files, etc.
Default Constructors A class can have
only one default
constructor
• A default constructor is a constructor that takes no
arguments

• If you write a class with no constructor at all, C++ will


write a default constructor for you, one that does nothing.

• A simple instantiation of a class (with no arguments)


calls the default constructor:
Rectangle r;
Parametrized Constructors

• To create a constructor that takes arguments:


• indicate parameters in prototype:

Rectangle(double, double);

• Use parameters in the definition:

Rectangle::Rectangle(double w, double len)


{
width = w;
length = len;
}
Parametrized Constructors

• You can pass arguments to the constructor when you


create an object:
Rectangle r(10.7, 5.2);

• Constructors can be overloaded


Rectangle(double w, double len, double ar)
{
width = w;
length = len;
area = ar;
}
Rectangle r(10.0, 5.0, 50.0);
More About Default Constructors

• If all of a constructor's parameters have default


arguments, then it is a default constructor. For example:

Rectangle(double len = 0, double wid = 0){


length = len; width = wid;
}

• Creating an object and passing no arguments will cause


this constructor to execute:

Rectangle r;

• Cannot create multiple default constructors - ERROR


More About Default Constructors

Rectangle(double len = 0, double wid = 0){


length = len; width = wid;
}

• Creating an object and passing no arguments will cause


this constructor to execute:

Rectangle r;
Rectangle r1(10.0);
Rectangle r2(10.0, 2.0);

All three cause the same constructor to execute


More About Default Constructors

Rectangle(double len = 0, double wid = 0){


length = len; width = wid;
}
With this constructor,
cannot create any other
• Creating an object and passing constructor
no arguments willorcause
with 0,1 2
this constructor to execute: parameters.
Because then the compiler
Rectangle r; cannot differentiate and
decide which one to call
Rectangle r1(10.0);
Rectangle r2(10.0, 2.0);

All three cause the same constructor to execute


Classes with No Default Constructor

• When all of a class's constructors require arguments,


then the class has NO default constructor.

• When this is the case, you must pass the required


arguments to the constructor when creating an object.
Destructors
• Member function automatically called when an object is
destroyed

• Destructor name is ~classname, e.g., ~Rectangle


• Has no return type; takes no arguments

• Only one destructor per class, i.e., it cannot be


overloaded
• If constructor allocates dynamic memory, destructor
should release it
Example InventoryItem.h
Example InventoryItem.h

(continued)
Constructors, Destructors, and
Dynamically Allocated Objects
• When an object is dynamically allocated with the new
operator, its constructor executes:

Rectangle *r = new Rectangle(10, 20);

• When the object is destroyed, its destructor executes:

delete r;
Only One Default Constructor
and One Destructor
• Do not provide more than one default constructor for a
class: one that takes no arguments and one that has
default arguments for all parameters
Square();
Square(int = 0); // will not compile

• Since a destructor takes no arguments, there can only


be one destructor for a class
Member Function Overloading

• Non-constructor member functions can also be


overloaded:
void setCost(double);
void setCost(char *);

• Must have unique parameter lists, like overloaded


constructors
When Constructors and Destructors Are
Called
Constructors and destructors called automatically
1.Global scope objects
• Constructors called before any other function
(including main)
• Destructors called when main terminates (or exit
function called)

2.Local scope objects


• Constructors called when objects are defined
• Destructors called when objects leave scope
7 class CreateAndDestroy {
8 public:
9 CreateAndDestroy( int ); // constructor
10 ~CreateAndDestroy(); // destructor
11 private:
12 int data;
13 };
14
15 #endif

24
25 CreateAndDestroy::CreateAndDestroy( int value )
26 { Constructor and Destructor
changed to print when they are
27 data = value; called.
28 cout << "Object " << data << " constructor";
29 }
30
31 CreateAndDestroy::~CreateAndDestroy()
32 { cout << "Object " << data << " destructor " << endl; }
63
64 // Function to create objects
65 void create( void )
66 {
67 CreateAndDestroy fifth( 5 );
68 cout << " (local in create)" << endl;
69
70
71
72
42 73 CreateAndDestroy seventh( 7 );
43 void create( void ); // prototype 74 cout << " (local in create)" << endl;
44 75 }
45 CreateAndDestroy first( 1 ); // global object
46
47 int main()
48 {
49 cout << " (global created before main)" << endl;
50
51 CreateAndDestroy second( 2 ); // local object
52 cout << " (local in main)" << endl;
53
54
55
56
57 create(); // call function to create objects
58
59 CreateAndDestroy fourth( 4 ); // local object
60 cout << " (local in main)" << endl;
61 return 0;
62 }
OUTPUT
Object 1 constructor (global created before main)
Object 2 constructor (local in main)
Object 5 constructor (local in create)
Object 7 constructor (local in create)
Object 7 destructor
Object 5 destructor
Object 4 constructor (local in main) Notice how the order of the
Object 4 destructor constructor and destructor call
Object 2 destructor
Object 1 destructor
depends on the types of variables
(local and global) they are
associated with.
Destructor Example

void f1()
{
Employee *c = new Employee[3];
c[0].var1 = 322;
c[1].var1 = 5
c[2].var1 = 9;lete [] c; //destructor
will call here
}
class Item {
private:
double cost;
int units;
public:
Item() { //Default Constructor
cost = 0.0;
units = 0; }

Item(int costVal){ //Constr 1 parameter


cost = costVal;
units = 0; }

Item(double c, int u) { //Constr 2 parameters


cost = c;
units = u; } };
Arrays of Objects

• Objects can be the elements of an array:

Item inventory[40];

• Default constructor for object is used when array is


defined
Arrays of Objects

• Must use initializer list to invoke constructor that takes


arguments:

Item inventory[3] =
{ 22.4, 10.30, 99.0 };

• The compiler treats each item in the initializer list as an


argument for an array element’s constructor

• Second constructor in the Item class


Arrays of Objects

• If the constructor requires more than one argument, the


initializer must take the form of a function call:

Item inventory[] = {Item(6.95, 12),


Item(8.75, 20),
Item(3.75, 10) };
Arrays of Objects

• It isn't necessary to call the same constructor for each


object in an array:

Item inventory[] = {20.5,


Item( 8.75, 20), 45.0};
Accessing Objects in an Array

• Objects in an array are referenced using


subscripts

• Member functions are referenced using dot


notation:

inventory[2].setUnits(30);

cout << inventory[2].getUnits();


Array of pointers to objects

• Declare an array of pointer to objects


• Allocate and initialize each object in a loop

Date *dates[31];

for (int day = 0; day < 31; ++day)


{
dates[day] = new Date(3, day, 2020);
}
Default Member-wise Assignment

• Assignment operator (=) can be used to assign an object


to another object of the same type.

• Member-wise assignment: each data member of the


object on the right of the assignment operator is
assigned individually to the same data member in the
object on the left
Default Member-wise Assignment
class Rectangle{
double length;
double width;
public:
Rectangle(){ //default constructor
length = 0; width = 0; }
//parametrized constructor
Rectangle(double l, double w) {
length = l;
width = w; }
}; box1
//box1 is an object of class Rectangle length = 10.0
Rectangle box1(10.0, 20.0); width = 20.0
Default Member-wise Assignment

//box1 is an object of class Rectangle


Rectangle box1(10.0, 20.0);

Rectangle box2;

box2 = box1;

box2 box1

length = 0.0 length = 10.0


width = 0.0 width = 20.0
Default Member-wise Assignment

//box1 is an object of class Rectangle


Rectangle box1(10.0, 20.0);

Rectangle box2;

box2 = box1;

Rectangle box3 = box2;

box3 box2 box1

length = 10.0 length = 10.0 length = 10.0


width = 20.0 width = 20.0 width = 20.0
Default Copy Constructor

• A copy constructor creates an object and initializes it


with another object’s data. Objects must be of the same
type

• If a class doesn’t have a copy constructor, C++ creates a


default copy constructor for it.

Rectangle box3 = box2; OR Rectangle box3(box2);

• The default copy constructor performs the member-


wise assignment when an object is initialized using
another object.
Copy constructor

• A type of constructor that is used to initialize an object


with another object of the same type is known as copy
constructor.

• It is by default available in all classes

• It has the same form as other constructors, except it has


a reference parameter of the same class type

• syntax is ClassName(ClassName &Variable)


Rectangle(Rectangle &r)
Copy Constructor for Class Date

Date::Date(Date &date)
{
month = date.month;
day = date.day;
year = date.year;
}
Uses of the Copy Constructor

• Implicitly called in 3 situations:


1. Dynamically defining a new object from an existing
object
2. passing an object by value
3. returning an object by value
Copy Constructor: Defining a New
Object
//parametrized constructor called
Date d1(2,28,2020);

// initialize 2 local objects from d1


Date d2(d1);// pass by value
Date d3 = d1;// return value

// init a dynamic object from d1


Date* pdate = new Date(d1);
Copy Constructor: Passing Objects by
Value
//copy constructor called for each value arg
int dateDiff(Date d1, Date d2);
...
Date today; //default constructor called
Date d3(02, 21, 2000); //parametrized constr.

cout << dateDiff(d3, today);


Some Issues with the Default Copy
Constructor
• There are instances, where the default copy constructor
can be problematic
class Student{
private:
char *name;
public:
Student(){ //default constructor
name = new char[12]{0};
}

void setName(char* nameVal){ //setter for name


int i=0;
while((*nameVal)!='\0'){
name[i++]=(*nameVal);
nameVal++; }
}
char* getName(){ //getter for name
return name; } };
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
Dynamically
allocated array
B r u c e W a y n e

return 0; }
int main(){ s1
s2’s default copy
Student s1;
constructor is called
and s1’s member
char name1[]="Bruce Wayne"; name
variable values are
s1.setName(name1);
copied in s2 Dynamically
allocated array
cout<<s1.getName()<<endl;
B r u c e W a y n e

Student s2 = s1;

name

s2
Output

Bruce Wayne

return 0; }
int main(){ s1
Student s1;Pointers in both
objects will point to
char name1[]="Bruce
the same addressWayne"; name
a.k.a shallow copy
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
B r u c e W a y n e

Student s2 = s1;
cout<<s2.getName()<<endl;
name

s2
Output

Bruce Wayne

return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
B r u c e W a y n e

Student s2 = s1;
cout<<s2.getName()<<endl;
name

s2
Output

Bruce Wayne
Bruce Wayne

return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
B r u c e W a y n e

Student s2 = s1;
cout<<s2.getName()<<endl;
name

char name2[]="Clark Kennt";


s2.setName(name2); s2
Output

Bruce Wayne
Bruce Wayne

return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
C l a r k K e n n t

Student s2 = s1;
cout<<s2.getName()<<endl;
name

char name2[]="Clark Kennt";


s2.setName(name2); s2
cout<<s2.getName()<<endl; Output

Bruce Wayne
Bruce Wayne

return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
C l a r k K e n n t

Student s2 = s1;
cout<<s2.getName()<<endl;
name

char name2[]="Clark Kennt";


s2.setName(name2); s2
cout<<s2.getName()<<endl; Output

Bruce Wayne
Bruce Wayne
Clark Kennt
return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
C l a r k K e n n t

Student s2 = s1;
cout<<s2.getName()<<endl;
name

char name2[]="Clark Kennt";


s2.setName(name2); s2
cout<<s2.getName()<<endl; Output
cout<<s1.getName()<<endl; Bruce Wayne
Bruce Wayne
Clark Kennt
return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
C l a r k K e n n t

Student s2 = s1;
cout<<s2.getName()<<endl;
name

char name2[]="Clark Kennt";


s2.setName(name2); s2
cout<<s2.getName()<<endl; Output
cout<<s1.getName()<<endl; Bruce Wayne
Bruce Wayne
Clark Kennt
return 0; } Clark Kennt
Some Issues with Default Copy
Constructor – Shallow Copy
• Either object can manipulate the values stored in the
array, causing the changes to show up in the other
object.

• One object can be destroyed, causing its destructor to


be called, which frees the allocated memory

• The remaining object’s name pointer would still reference


this section of memory, although it should no longer be
used
User-defined Copy Constructor,
required?
• Default-copy Constructor do only “Shallow Copy”
• We need user-defined copy-constructor,
• When we need “Deep Copy” (for Dynamic Memory)
User defined Copy Constructor – Deep
Copy
class Student{
private:
char *name;
public:
Student(){ //default constructor
name = new char[12]{0};
}
Student(const Student &s){ //copy constructor
name = new char[12]; //for deep copy
for (int i = 0; i < 12; i++) {
name[i] = s.name[i]; }
}
};
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
B r u c e W a y n e

Student s2 = s1;
cout<<s2.getName()<<endl; B r u c e W a y n e

char name2[]="Clark Kennt";


s2.setName(name2); name

Output
s2 Bruce Wayne
Bruce Wayne
return 0; }
int main(){ s1
Student s1;
char name1[]="Bruce Wayne"; name
s1.setName(name1); Dynamically
allocated array
cout<<s1.getName()<<endl;
B r u c e W a y n e

Student s2 = s1;
cout<<s2.getName()<<endl; C l a r k K e n n t

char name2[]="Clark Kennt";


s2.setName(name2); name
cout<<s2.getName()<<endl; Output
cout<<s1.getName()<<endl; s2 Bruce Wayne
Bruce Wayne
Clark Kennt
return 0; }
Bruce Wayne
Shallow Copy
1. class Demo
2. {
3. int a;
4. int b;
5. int *p;
6. public:
7. Demo()
8. {
9. p=new int;
10. }
11. void setdata(int x,int y,int z)
12. {
13. a=x;
14. b=y;
15. *p=z;
16. }
17. void showdata() 24. int main()
18. { 25. {
26. Demo d1;
19. std::cout << "value of a is : " <<a<< std::endl;
27. d1.setdata(4,5,7);
20. std::cout << "value of b is : " <<b<< std::endl; 28. Demo d2 = d1;
21. std::cout << "value of *p is : " <<*p<< std::endl; 29. d2.showdata();
22. } 30. return 0;
23. }; 31. }
Deep Copy
1. class Demo
2. {
3. public:
4. int a;
5. int b;
6. int *p;
7.
8. Demo()
9. {
10. p=new int;
11. }
12. Demo(Demo &d)
13. {
14. a = d.a;
15. b = d.b;
16. p = new int;
17. *p = *(d.p);
18. }
19. void setdata(int x,int y,int z)
20. {
21. a=x;
22. b=y;
23. *p=z;
24. }
Deep Copy
1.
2. void showdata()
3. {
4. std::cout << "value of a is : " <<a<< std::endl;
5. std::cout << "value of b is : " <<b<< std::endl;
6. std::cout << "value of *p is : " <<*p<< std::endl;
7. }
8. };
9. int main()
10.{
11. Demo d1;
12. d1.setdata(4,5,7);
13. Demo d2 = d1;
14. d2.showdata();
15. return 0;
16.}
Copy Constructor for Class Date

• Copy constructors have to use reference parameters so


they have access to their argument’s data.

• To prevent the copy constructor from modifying the


arguments data, make the copy constructors’ parameters
constant

Date::Date(const Date &date)


{ month = date.month;
day = date.day;
year = date.year;
}
Class Instance Variables (Attributes)

class Car { Car car1, car2, car3;


int fuel;
public:
string model;
Car() { //constructor
fuel = 0;
model = “”;}
};

fuel=0; fuel=0; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


Class Instance Variables (Attributes)

class Car { Car car1, car2, car3;


int fuel;
public:
string model; //assume class has a
Car() { //constructor setter
fuel = 0; car1.setFuel(50);
model = “”;}
};

fuel=0; fuel=0; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


Class Instance Variables (Attributes)

class Car { Car car1, car2, car3;


int fuel;
public:
string model; //assume class has a
Car() { //constructor setter
fuel = 0; car1.setFuel(50);
model = “”;} car2.setFuel(30);
};

fuel=50; fuel=0; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


Class Instance Variables (Attributes)

class Car { Car car1, car2, car3;


int fuel;
public:
string model; //assume class has a
Car() { //constructor setter
fuel = 0; car1.setFuel(50);
model = “”;} car2.setFuel(30);
}; car3.setFuel(84);

fuel=50; fuel=30; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


Each class object
has its own copy of
Class Instance Variables (Attributes)
the class’s member
variables.

class Car { Car car1, car2, car3;


int fuel;
public:
string model; //assume class has a
Car() { //constructor setter
fuel = 0; car1.setFuel(50);
model = “”;} car2.setFuel(30);
}; car3.setFuel(84);

fuel=50; fuel=30; fuel=84;


model=“”; model=“”; model=“”;

car1 car2 car3


static Class Members

• Class members include instance variables and functions

• It is possible to create a member variable or member


function that does not belong to any instance of a
class.

• Such members are known as a static member variables


and static member functions.

• You can think of static class members as belonging to


the class instead of to an instance of the class
static Member Variables

• When a member variable is static, there will be only one


copy of it in memory, regardless of the number of
instances of the class that might exist.

• A single copy of a class’s static member variable is


shared by all objects of the class

• Static member variables exist even if no instances


(objects) of the class exist
class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”; }
};
int Car::totalCars; totalCars = 0
(static)

fuel=0; fuel=0; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
}; totalCars = 0
int Car::totalCars; (static)

fuel=0;
model=“”;

car1
class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
}; totalCars = 1
int Car::totalCars; (static)

fuel=0;
model=“”;

car1
class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
}; totalCars = 1
int Car::totalCars; (static)

fuel=0; fuel=0;
model=“”; model=“”;

car1 car2
class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
}; totalCars = 2
int Car::totalCars; (static)

fuel=0; fuel=0;
model=“”; model=“”;

car1 car2
class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
}; totalCars = 2
int Car::totalCars; (static)

fuel=0; fuel=0; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


class Car { Car car1,car2,car3;
int fuel;
string model;
static int totalCars;
public:
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
}; totalCars = 3
int Car::totalCars; (static)

fuel=0; fuel=0; fuel=0;


model=“”; model=“”; model=“”;

car1 car2 car3


static Member Variables

• Shared by all objects of a class

• Efficient, when a single copy of data is enough


• Only the static variable has to be updated

• May seems like global variables, but have class scope


• only accessible to objects of same class

• Exist even if no instances (objects) of the class exist

• Can be public or private


This external definition
static Member Variables statement causes the
variable to be created
in memory and is
required.
• Two-Step Procedure:
1. Declare (Inside Class): static int radius;
2. Define (Outside Class): int Circle::radius;

• Static Variables
• Default Initialization: 0 or Null (for pointers)
• Initialization: user defined value
• Initialization is made just once, at compile time.
• Accessibility: Private or Public
Public static Member Variables

• Can be accessed using class name:


cout << Car::totalCars;

• Can be accessed via any class’ object:


cout << car1.totalCars;

• Can be accessed via Non-Static member functions:


• Must create object first
cout << car1.getCars();

• Can be accessed via Static member functions:


cout << Car::getTotalCars();
cout << car1.getTotalCars(); //public static
Private static Member Variables

• Cannot be accessed using class name:


// ERROR  cout << Car::totalCars;

• Cannot be accessed via class' object:


// ERROR  cout << car1.totalCars;

• Can be accessed via Non-Static member functions:


Must create object first
cout << car1.getCars();

• Can be accessed via Static member functions:


cout << Car::getTotalCars();
cout << car1.getTotalCars(); //public static
static Member Variables

• The lifetime of a class’s static member variable is the


lifetime of the program

• This means that a class’s static member variables come


into existence before any instances of the class are
created
static Member Functions

• Static member functions can operate only on static


member variables.

• You can think of static member functions as belonging to


the class instead of to an instance of the class.

• Static member functions can be called without creating


any class objects
static Member Functions
class Car {
int fuel;
string model;
static int totalCars;
Car() { //constructor
fuel = 0;
model = “”;
totalCars++; }
static int getTotalCars(){
return totalCars; //only access static members
}
};
int Car::totalCars;
static Member Functions

• Non-static function:
• Can access: all class members

• Static functions:
• Can access: static data and static functions
• Cannot access: non-static data, non-static functions,
and this pointer
Public static Member Functions

• Can be invoked using any class object:


cout << car1.getTotalCars();

• Can be invoked using class name:


cout << Car:: getTotalCars();
Private static Member Functions

• Cannot be invoked using class objects


//ERROR  cout << e1.getCount();

• Cannot be invoked using class name


//ERROR  cout << Employee::getCount();

• Can be invoked within class:


• Static member functions
• Non-static member functions
1 // Fig. 7.9: employ1.h
2 // An employee class
3 #ifndef EMPLOY1_H
4 #define EMPLOY1_H
5
6 class Employee {
7 public:
8 Employee( const char*, const char* ); // constructor
9 ~Employee(); // destructor
10 const char *getFirstName() const; // return first name
11 const char *getLastName() const; // return last name
12
13 // static member function
14 static int getCount(); // return # objects instantiated
15
16 private: static member function and
17 char *firstName;
variable declared.
18 char *lastName;
19
20 // static data member
21 static int count; // number of objects instantiated
22 };
23
24 #endif
25 // Fig. 7.9: employ1.cpp
26 // Member function definitions for class Employee
27 #include <iostream>
28
29 using std::cout;
30 using std::endl; static data member count and
31 function getCount( ) initialized
32 #include <cstring> (required).
33 #include <cassert>
34 #include "employ1.h"
35
36 // Initialize the static data member
37 int Employee::count = 0;
38
39 // Define the static member function that
40 // returns the number of employee objects instantiated.
41 int Employee::getCount() { return count; }
42
43 // Constructor dynamically allocates space for the
44 // first and last name and uses strcpy to copy
45 // the first and last names into the object
46 Employee::Employee( const char *first, const char *last )
47 {
48 firstName = new char[ strlen( first ) + 1 ];
49 assert( firstName != 0 ); // ensure memory allocated
50 strcpy( firstName, first ); static data member
51 count changed when a
52 lastName = new char[ strlen( last ) + 1 ];
53 assert( lastName != 0 ); // ensure memory allocated
constructor/destructor
54 strcpy( lastName, last ); called.
55
56 ++count; // increment static count of employees
57 cout << "Employee constructor for " << firstName
58 << ' ' << lastName << " called." << endl;
59 }
60
61 // Destructor deallocates dynamically allocated memory
62 Employee::~Employee() static data member count
63 { changed when a
64 cout << "~Employee() called for " << firstName constructor/destructor called.
65 << ' ' << lastName << endl;
66 delete [] firstName; // recapture memory
67 delete [] lastName; // recapture memory Count decremented
68 --count; // decrement static count of employees
because of
69 } destructor calls from
70 delete.
71 // Return first name of employee
72 const char *Employee::getFirstName() const
73 {
74 // Const before return type prevents client from modifying
75 // private data. Client should copy returned string before
76 // destructor deletes storage to prevent undefined pointer.
77 return firstName;
78 }
79
80 // Return last name of employee
81 const char *Employee::getLastName() const
82 {
83 // Const before return type prevents client from modifying
84 // private data. Client should copy returned string before
85 // destructor deletes storage to prevent undefined pointer.
86 return lastName;
87 }
88 // Fig. 7.9: fig07_09.cpp
89 // Driver to test the employee class
90 #include <iostream> If no Employee objects exist
91 count incremented because of getCount must be accessed
92 using std::cout; constructor calls from new. using the class name and (::).
93 using std::endl;
94
95 #include "employ1.h"
96 Number of employees before instantiation is 0
97 int main()
98 {
99 cout << "Number of employees before instantiation is "
100 << Employee::getCount() << endl; // use class name
e2Ptr->getCount() or Employee::getCount() would
101 also work.
102 Employee *e1Ptr = new Employee( "Susan", "Baker" );
103 Employee *e2Ptr = new Employee( "Robert", "Jones" );
104 Number of employees after instantiation is 2
105 cout << "Number of employees after instantiation is "
106 << e1Ptr->getCount();
107 Employee constructor for Susan Baker called.
108 cout << "\n\nEmployee 1: " Employee constructor for Robert Jones called.
109 << e1Ptr->getFirstName()
110 << " " << e1Ptr->getLastName() Employee 1: Susan Baker
111 << "\nEmployee 2: " Employee 2: Robert Jones
112 << e2Ptr->getFirstName()
113 << " " << e2Ptr->getLastName() << "\n\n";
114
115 delete e1Ptr; // free memory ~Employee() called for Susan Baker
116 e1Ptr = 0; ~Employee() called for Robert Jones
117 delete e2Ptr; // free memory
118 e2Ptr = 0;
119

120 cout << "Number of employees after deletion is "

121 << Employee::getCount() << endl;

122

123 return 0;
count back to zero.
124 }

Number of employees before instantiation is 0


Employee constructor for Susan Baker called.
Employee constructor for Robert Jones called.
Number of employees after instantiation is 2

Employee 1: Susan Baker


Employee 2: Robert Jones

~Employee() called for Susan Baker


~Employee() called for Robert Jones
Number of employees after deletion is 0
static Class Members

Calling a static member


function of a class using
the object

Calling a static member


function of a class using
the class name
this Pointer

• The this pointer is a special built-in pointer that is


available to a class’s non-static member functions.

• It always points to the instance of the class making the


function call.

• The this pointer is passed as a hidden argument to all


non-static member functions.
void setFuel(int fuel, Car* const this) {

this->fuel = fuel;
}
this Pointer
void setFuel(int fuel, Car* const this) {

this->fuel = fuel;
}

Car car1, car2;

car1.setFuel(20); // this pointer points at car1


car2.setFuel(40); // this pointer points at car2

• this pointer is a constant pointer that references to the


calling object.
Using the this Pointer
• Not part of the object itself

• Can be used to access instance variables within member


functions (including constructors and destructors)

• this pointer stores the address of the calling object

• For a member function print data member x, either


this->x;
or
(*this).x
Using the this Pointer
• Useful when function parameters and class member
variables have the same name

//Parametrized Constructor
Car(int fuel, string model) {
this->fuel = fuel;
this->model = model;

}
Using the this Pointer
• Function returns a reference pointer to the same object
{ return *this; }

• Other functions can operate on that pointer


• Useful for cascading functions - multiple functions
called on the same object
1 // Fig. 7.7: fig07_07.cpp
2 // Using the this pointer to refer to object members.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 class Test {
9 public:
10 Test( int = 0 ); // default constructor
11 void print() const;
12 private:
13 int x;
Printing x directly.
14 };
15
16 Test::Test( int a ) { x = a; } //default constructor implementation
17
18 void Test::print() const // ( ) around *this required Print x using the arrow ->
19 { operator off the this pointer.
20 cout << " using variable = " << x
21 << "\n using this pointer = " << this->x
22 << "\n using this with * = " << ( *this ).x << endl;
23 }
24
25 int main()
26 {
27 Test testObject( 12 );
28 Printing x using the dot (.) operator. Parenthesis
29 testObject.print(); required because dot operator has higher
30 precedence than *. Without, interpreted
31 return 0; incorrectly as *(this.x).
32 }
using variable = 12
using this pointer = 12
using this with * = 12

All three methods


have the same result.
1 // Fig. 7.8: time6.h
2 // Cascading member function calls.
3
4 // Declaration of class Time.
5 // Member functions defined in time6.cpp
6 #ifndef TIME6_H
7 #define TIME6_H
8
9 class Time {
10 public:
11 Time( int = 0, int = 0, int = 0 ); // default constructor
12
13 // set functions
14 Time &setTime( int, int, int ); // set hour, minute, second
15 Time &setHour( int ); // set hour
16 Time &setMinute( int ); // set minute
17 Time &setSecond( int ); // set second Noticethe Time & - function
18
returns a reference to a Time
19 // get functions (normally declared const)
20 int getHour() const; // return hour object.
21 int getMinute() const; // return minute Specify object in function definition.
22 int getSecond() const; // return second
23
24 // print functions (normally declared const)
25 void printMilitary() const; // print military time
26 void printStandard() const; // print standard time
27 private:
28 int hour; // 0 - 23
29 int minute; // 0 - 59
30 int second; // 0 - 59
31 };
32
33 #endif
34 // Fig. 7.8: time.cpp
35 // Member function definitions for Time class.
36 #include <iostream>
37
38 using std::cout;
39
40 #include "time6.h"
41
42 // Constructor function to initialize private data.
43 // Calls member function setTime to set variables.
44 // Default values are 0 (see class definition).
45 Time::Time( int hr, int min, int sec )
46 { setTime( hr, min, sec ); }
47
48 // Set the values of hour, minute, and second.
49 Time &Time::setTime( int h, int m, int s )
Returning *this enables
50 { cascading function calls
51 setHour( h );
52 setMinute( m );
53 setSecond( s );
54 return *this; // enables cascading
55 }
56
57 // Set the hour value
58 Time &Time::setHour( int h )
59 {
60 hour = ( h >= 0 && h < 24 ) ? h : 0;
61
62 return *this; // enables cascading
63 }
64
65 // Set the minute value
66 Time &Time::setMinute( int m )
67 {
68 minute = ( m >= 0 && m < 60 ) ? m : 0;
69
70 return *this; // enables cascading
71 }
72
73 // Set the second value
Returning *this enables
74 Time &Time::setSecond( int s )
cascading function calls
75 {
76 second = ( s >= 0 && s < 60 ) ? s : 0;
77
78 return *this; // enables cascading
79 }
80
81 // Get the hour value
82 int Time::getHour() const { return hour; }
83
84 // Get the minute value
85 int Time::getMinute() const { return minute; }
86
87 // Get the second value
88 int Time::getSecond() const { return second; }
89
90 // Display military format time: HH:MM
91 void Time::printMilitary() const
92 {
93 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
94 << ( minute < 10 ? "0" : "" ) << minute;
Using the this Pointer

• Example of cascaded member function calls:

• Member functions setHour, setMinute, and setSecond all return *this


(reference to an object)

• For object t, consider:


t.setHour(1).setMinute(2).setSecond(3);

• Executes t.setHour(1), returns *this (reference to object) and the


expression becomes
t.setMinute(2).setSecond(3);

• Executes t.setMinute(2), returns reference and becomes


t.setSecond(3);

• Executes t.setSecond(3), returns reference and becomes


t; (Has no effect)
95 }
96
97 // Display standard format time: HH:MM:SS AM (or PM) printStandard does not
98 void Time::printStandard() const return a reference to an object.
99 {
100 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
101 << ":" << ( minute < 10 ? "0" : "" ) << minute
102 << ":" << ( second < 10 ? "0" : "" ) << second
103 << ( hour < 12 ? " AM" : " PM" );
104 }
105 // Fig. 7.8: fig07_08.cpp
106 // Cascading member function calls together
107 // with the this pointer
108 #include <iostream> Notice cascading function calls.
109
110 using std::cout;
111 using std::endl;
112
113 #include "time6.h"
114
115 int main()
116 {
117 Time t;
118
119 t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
120 cout << "Military time: "; Cascading function calls. printStandard must be called
121 t.printMilitary(); after setTime because printStandard does not return
122 cout << "\nStandard time: "; a reference to an object.
123 t.printStandard(); t.printStandard().setTime(); would cause an
124 error.
125 cout << "\n\nNew standard time: ";
126 t.setTime( 20, 20, 20 ).printStandard();
127 cout << endl;

128

129 return 0;

130 }

Military time: 18:30


Standard time: 6:30:22 PM

New standard time: 8:20:20 PM


Member Initializer List

• You have used initializer lists with arrays

int arr[] = {1,2,3,4,5};

• The data members of a class can also be initialized


using an initializer list with the constructor
Member Initializer List
class Test {
int marks;
int total;

public:
//inline with initializer list
Test() : marks(0),total(0) {} //default constructor

Test(int m, int t) : marks(m), total(t) {}

int getMarks() {
return marks;
}
int getTotal() {
return total;
}
};
Member Initializer List
class Test {
int marks;
int total;

public:
//inline with initializer list
Test() : marks(0),total(0) {} //default constructor

Test(int m, int t) : marks(m), total(t) {}

int getMarks() {
return marks;
}
int getTotal() {
return total;
}
};
Member Initializer List
class Test {
int marks;
int total;

public:
Test(); //prototype
Test(int, int ); //prototype
int getMarks() {
return marks;
}
int getTotal() {
return total;
}
};
//out of line with initializer list
Test::Test() :marks(0), total(0) {}
Test::Test(int m,int t): marks(m), total(t) {}
Member Initializer List (Non-const
Members)
When to use Member Initializer List

• You can use initializer list to initialize member variables


but it is not necessary

• But you must use an initializer list for


• Initializing a constant data member
• Initializing a reference member
const Class Members

• As with member functions, data members can also be


const

• Constant members must be initialized using member


initializer list
Member Initializer List (non-static const)
Member Initializer List (References)
Member Initializer List
(parameter name same as data member)
const Objects

• Read-only objects

• Object data members can only be read, NO


write/update of data member allowed

• Requires all member functions be const (except


constructors and destructors)

• const object must be initialized (using constructors) at


the time of object creation
const Objects

• const property of an object goes into effect after the


constructor finishes executing and ends before the
class's destructor executes
• So the constructor and destructor can modify the
object
friend Functions and friend Classes

• A friend is a function or class that is not a member of a


class, but has access to the private members of the
class

• In other words, a friend function is treated as if it were a


member of the class

• A friend function can be a regular stand-alone function,


or it can be a member of another class.

• An entire class can also be declared a friend of another


class
friend Functions and friend Classes

• To declare a friend function


• Type friend before the function prototype in the class that
is giving friendship
friend int myFunction( int x );
• should appear in the class giving friendship

• To declare a friend class


• Type friend class Classname in the class that is giving
friendship
• if ClassOne is granting friendship to ClassTwo,
friend class ClassTwo;
• should appear in ClassOne's definition
friend Functions and friend Classes

• friend functions and friend classes


• Can access private members of another class

• Properties of friendship
• Friendship is granted, not taken
• Not symmetric (if B a friend of A, A not necessarily
a friend of B)
• Not transitive (if A a friend of B, B a friend of C, A
not necessarily a friend of C)
1 // Fig. 7.5: fig07_05.cpp
2 // Friends can access private members of a class.
3 #include <iostream> setA a friend of class Count
4 (can access private data).
5 using std::cout;
6 using std::endl;
7
8 // Modified Count class
9 class Count {
10 friend void setA( Count &, int ); // friend function declaration
11 public:
12 Count() { a = 0; } // constructor
13 void print() const { cout << x << endl; } // output
14 private:
15 int a; // data member
16 }; setA is defined normally and is
17 not a member function of
18 // Can modify private data of Count because Count.
19 // setX is declared as a friend function of Count
20 void setA( Count &c, int val ) Changing private variables allowed.
21 {
22 c.x = val; // legal: setX is a friend of Count
23 }
24
25 int main()
26 {
27 Count counter;
28
29 cout << "counter.a after instantiation: ";
30 counter.print();
31 cout << "counter.a after call to setA friend
function: ";
32 setA( counter, 8 ); // set a with a friend

33 counter.print();

34 return 0;

35 }

counter.a after instantiation: 0


counter.a after call to setA friend function: 8

private data was changed.


1 // Fig. 7.6: fig07_06.cpp
2 // Non-friend/non-member functions cannot access
3 // private data of a class.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl; cannotSetA is not a friend of class
8 Count. It cannot access private data.
9 // Modified Count class
10 class Count {
11 public:
12 Count() { x = 0; } // constructor
13 void print() const { cout << x << endl; } // output
14 private:
15 int x; // data member
16 };
17
18 // Function tries to modify private data of Count,
19 // but cannot because it is not a friend of Count.
20 void cannotSetA( Count &c, int val )
21 {
22 c.x = val; // ERROR: 'Count::x' is not accessible
23 }
24
cannotSetA tries to modify a
25 int main() private variable…
26 {
27 Count counter;
28
29 cannotSetX( counter, 3 ); // cannotSetX is not a friend
30 return 0;
31 }
Compiling...
Fig07_06.cpp
D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\Fig07_06.cpp(22) :
error C2248: 'x' : cannot access private member declared in
class 'Count'
D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\
Fig07_06.cpp(15) : see declaration of 'x'
Error executing cl.exe.

test.exe - 1 error(s), 0 warning(s)

Expected compiler error - cannot access


private data
friend Functions and friend Classes

• Friends should be used only for limited purpose

• Too many functions declared as friends with private data


access, lessens the value of encapsulation

You might also like