Chapter 4 Classes
Chapter 4 Classes
Chapter 4 Classes
Fundamentals of Programming II
Chapter Four
Classes
1
January 2014
Introduction
In traditional programming, programs are basically
lists of instructions to the computer that define data
and then work with that data.
Everywhere you look are objects.
Most objects have two major components to them:
A list of properties (eg. weight, color, size, texture,
etc…), and
Some number of actions that either they can
perform, or that can be performed on them (eg.
being opened, having something poured into it,
etc…)
They are inseparable 2
In traditional programming, properties (data) and
actions (functions) are separate entities
OO Programming Concepts
Aim of C++ class concept is to provide the
programmer with a tool for creating new types
that can be used as conveniently as the built-in
types.
Object-oriented programming (OOP) provides
- ability to design “objects” that have both
characteristics (sometimes called attributes,
fields, or properties) and behaviors
(methods or features)
- Encapsulates data (attributes) and functions
3
(behavior) into packages called classes
- Inheritance, abstraction, and polymorphism
Contd…
An object represents an entity in the real world
that can be distinctly identified.
E.g., a student, a desk, bank-account, a
circle, a button, and even a loan
An object has a unique identity, state, and
behaviors
The state of an object consists of a set of data
fields (properties) with their current values
The behavior of an object is defined by a set of
functions 4
Structure Definitions
Structure
- Represent traditional non-OOP world
- They can only to hold data
- If you want to initialize or manipulate this data,
you have to have functions take them as parameter.
- Syntax
struct Time {
Structure tag
int hour;
int minute;
int second; Structure
members 5
};
Classes
While C++ provides a number of basic data types that
are often sufficient for solving relatively simple
problems, it can be difficult to solve complex
problems
C++ allow to define your own data types that better
correspond to the complex problem
Classes enables to model objects that have:
- attributes (represented by data members).
- behaviors or operations (represented by
member functions).
Every object belongs to a class 6
A class is the equivalent of a built-in data type (int,
float)
Contd…
An object is the equivalent of a variable of a data
type (i1,age)
Classes are very much like struct, except that
classes provide much more power and flexibility
A class is a category of objects; provides
a description of an object
a convenient way to group related data and the
functions that use the data
When you create an object from the class, you
automatically create all the related fields
You think about them & manipulate them as real- 7
Data Fields:
radius is _______
Functions:
getArea
CLASS-NAME :: IDENTIFIER;
Using Static Class Members
When a class field is static, only one
memory location is allocated
o All members of the class share a single
storage location for a static data member
of that same class
When you create a non-static variable
within a function, a new variable is create
every time you call that function
When you create a static variable, the
19
variable maintains its memory address and
previous value for the life of the program
Defining Static Data Members
20
Defining Static Data Members
the class
Using Static Functions
A static function can be used without a
declared object
Non-static functions can access static
variables (provided there is an object)
Static functions cannot access non-static
variables
22
Using Static Functions
23
static Class Members
• static data member
• Only one copy of a variable shared by all objects of a class
• “Class-wide” information
• A property of the class shared by all instances, not a property of a
specific object of the class
• Declaration begins with keyword static
24
static Class Members
• static member function
• Is a service of the class, not of a specific object of the class
• static applied to an item at file scope
• That item becomes known only in that file
• The static members of the class need to be available from any
client code that accesses the file
• So we cannot declare them static in the .cpp file—we declare
them static only in the .h file.
25
static Class Members
26
1 // Fig. 10.21: Employee.h
2 // Employee class definition.
3 #ifndef EMPLOYEE_H
4 #define EMPLOYEE_H
5
6 class Employee
7 {
8 public:
9 Employee( const char * const, const char * const ); // constructor
10 ~Employee(); // destructor
11 const char *getFirstName() const; // return first name
12 const char *getLastName() const; // return last name
13
14 // static member function
15 static int getCount(); // return number of objects instantiated
16 private:
17 char *firstName;
18 char *lastName; Function prototype for static member function
19
20 // static data
21 static int count; // number of objects instantiated
22 }; // end class Employee
23
24 #endif static data member keeps track of number
of Employee objects that currently exist 27
1 // Fig. 10.22: Employee.cpp
2 // Member-function definitions for class Employee.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include <cstring> // strlen and strcpy prototypes
8 using std::strlen;
9 using std::strcpy;
10
11 #include "Employee.h" // Employee class definition
12
13 // define and initialize static data member at file scope
14 int Employee::count = 0;
15
static
16 // define static member function that datanumber
returns member
of is defined and
17 // Employee objects instantiated initialized at file scope
(declared static in the .cpp file
in Employee.h)
18 int Employee::getCount()
19 {
20 return count;
21 } // end static function getCount
31
#include <iostream.h>
class Test
{
static int count; // count is static
public:
void increment()
{
count++;
}
static void display()
{
cout << "Counter : " << count << endl;
32
}
};
int Test::count; // class variable count defined outside
int main()
{
Test a, b;
a.increment();
Test::display();
b.increment();
Test::display();
return 0;
}
Output :
Counter : 1 33
Counter : 2
Friends
A friend of a class X is a function or class
that is not a member of X, but is granted the
same access to X as the members of X
Functions declared with the friend
specifier in a class member list are called
friend functions of that class
Classes declared with the friend friend
specifier in the member list of anther class
are called friend classes of that class.
34
Friend Function
used for accessing the non-public members of a
class.
The private and protected members of a class
cannot be accessed from outside the class in
which they are declared.
This rule doesn’t apply to friends
We can allow an external function access to the
private and protected members of the class by
declaring it as a friend to a class
We make an external function friend to a class by
declaring a prototype of this external function
35
with the class, and preceding it with the keyword
friend.
Friend Function
The keyword friend is placed only in the function
declaration of the friend function and not in the function
definition.
It is possible to declare a function as friend in any number
of classes
When a class is declared as a friend, the friend class has
access to the private data of the class that made this a
friend.
A friend function, even though it is not a member
function, would have the rights to access the private
members of the class
It can be invoked like a normal function without the help
of any object 36
The friend function generally has its arguments as objects
It can be declared in private or public part of the class
Example: External friend function
#include <iostream.h>
class test {
int a, b;
public:
void set() {
a = 10;
b = 20;
}
friend int average(test t); /* FRIEND function*/ 37
};
int average(test t) {
return (t.a + t.b) / 2;
}
int main()
{
test T;
T.set();
cout << "Average : " << average(T) << endl;
return 0;
38
}
classes
#include <iostream.h>
class High {
int h;
public: void set(int i) {
h = i; }
friend int average(High, Low);
};
class Low {
int l;
public: void set(int i) { 39
l = i; }
friend int average(High, Low);
};
int average(High high, Low low) {
return (high.h + low.l) / 2;
}
int main() {
High high;
Low low;
high.set(100);
low.set(10);
cout << "average : " << average(high, low) << endl; 40
return 0; }
Constructors
Used to initialize a new objects, allocating free
store by using new, either
int my_int=7; or
int my_int(7);
Must have,
- the same name as the class
- no return type – not even void
- public access
class car {
public:
car(int x=0, int y=0);
static int num_cars;
41
... }
A constructor function is the place to initialise all data members
Constructors
constructor without arguments called a no-arg
or no-argument constructor
constructors can be overloaded (i.e., multiple
constructors with the same name but different
signatures), making it easy to construct objects
with different initial data values.
A class may be declared without constructor.
In this case, a no-arg constructor with an empty
body is implicitly declared in the class – called
default constructor, is provided automatically
42
only if no constructors are explicitly declared in
the class
Classes
class ModInt with Constructors
{
public:
ModInt(int i); // constructor declaration
void assign(int i) { v = i % modulus; }
void print() const {cout << v << ‘\n’; }
const static int modulus;
private:
int v;
};
ModInt::ModInt(int i) { v = i % modulus; } // constructor 43
definition
const int ModInt::modulus = 60;
Classes
void main()with Constructors
{
ModInt a(5);
ModInt b(62);
a.print();
b.print();
}
What does the output look like?
5
2 44
Classes with Constructors
What happens if we declare a variable c as
follows:
ModInt c;
Since this class has only one constructor, and
this constructor needs one int argument, this
declaration causes a compile-time error.
The declaration above requires a default
constructor.
45
Default Constructors
A constructor requiring no arguments is called
the default constructor
It can be a constructor with an empty argument
list or one whose arguments all have default
values.
It has the special purpose of initializing arrays
of objects of its class.
In the ModInt example,
In the ModInt example, it would be useful to
define a default value of v to be 0. 46
To achieve this, we could add the following
default constructor:
The Default Constructor
• A constructor requiring no arguments is called the
default constructor.
• It can be a constructor with an empty argument list or
one whose arguments all have default values.
• It has the special purpose of initializing arrays of
objects of its class.
•In the ModInt example, it would be useful to define a default value of v to
be 0.
•To achieve this, we could add the following default constructor:
•ModInt() { v = 0; }
47
The Default Constructor
•main () Output:
•{
• ModInt s1, s2; 0
• ModInt d[5];
0
• ModInt s1.print();
0
• ModInt s2.print();
• ModInt d[3].print();
•}
48
The Default Constructor
• If a class does not have a constructor, the system
provides a default constructor.
• If a class has constructors but no default constructor,
array allocation causes a syntactic error.
•In our ModInt example, the following constructor could serve as both a
general initializer and a default constructor:
•ModInt(int i = 0) { v = i % modulus; }
49
Examples & Warning
car c1(5,5);
constructs a new car, c1 with initial position set
to 5,5
car c2;
54
Copy Constructor
The normal constructor never gets called when
making a copy
We usually do not need to write our own copy
constructor
A default exists which copies everything for you
Pointers included
Copy constructor only gets called if a new object
is constructed, not every time an object is copied
to another
(copy assignment operator – another day) 55
Copy Constructor
A function which
- Has a single parameter, a constant reference to
an object of the class
class car {
public:
car(int x=0, int y=0); //
constructor
car(const car &original); // copy
constructor
...
car c1(5,5);
car c2 = c1;
56
Car c2 will also have position 5,5 and face North
A copy constructor copies the object for us
Destructors
Like a constructor but called when an object is
destroyed
It deallocates store assigned to the object by
using delete
Given the class name with a ~ prefix
Called automatically cannot take or return
parameters
car::~car()
{
num_cars--; 57
}
Constructors and Destructors
Do not have a return types and cannot use return
expression statements
Constructors
Can take arguments
Can be overloaded
Invoked whenever
its associated type is used in a definition
Destructors
Can not take arguments
Can not be overloaded 58
Invoked implicitly whenever an object goes out of
scope
Defining a Class’ Functions
Need to specify that the function is from the
car class
Use the scope operator, ::
Otherwise it is just like a normal function
definition
void car::drive_forward()
{
if(heading==east) pos.x++;
// ... 59
}
Scope Operator ::
As used with namespaces,
std:: cout << "Hello World";
To define and use functions from a class
we also use the scope operator
void car::drive_forward()
{
if(heading==east) pos.x++;
if(heading==west) pos.x--;
// ... 60
}
Scope Operator ::
class car {
void print();
};
class city {
void print();
};
void print() {
cout << "test" << endl;
}
void car::print() {
cout << "test car" << endl;
}
void city::print() { 61
cout << "test city" << endl;
}
Protected Modifier
Class members designated protected are
available to derived classes (but not other
classes)
class vehicle {
public:
vehicle();
bool drive_forward();
bool change_lane_down();
bool change_lane_up();
int get_lane();
int get_distance();
protected:
int lane; 62
int distance;
};
const Objects and const Member Functions
Principle of least privilege
- Only allow modification of necessary objects
Keyword const
- Specify object not modifiable
- Compiler error if attempt to modify const
object
- Example
const Time noon(12,0,0);
- Declares const object noon of class Time 63
- Initializes to 12
const Objects and const Member Functions
const member functions
- Member functions for const objects must
also be const
- Cannot modify object
Specify const in both prototype and
definition
- Prototype
- After parameter list
- Definition 64
- Before beginning left brace
const Objects and const Member Functions
Constructors and destructors
- Cannot be const
- Must be able to modify objects
- Constructor
- Initializes objects
- Destructor
- Performs termination housekeeping
65
Summary
Classes
- Declare member functions and data ‘inside’
the class keyword
- Define static data and functions outside with
the :: operator
- Define object data in the constructor
Access modifiers
- Public, private, protected
- Aim to hide data – class is an independent 66
entity
Summary
Constructor
- Initialize object data
Copy constructor
- Default copies everything – including
pointers Destructor
Destructor
- Free resources
67
Thank You !!!
Any Questions
??
68