Вы находитесь на странице: 1из 68

ITec 2042

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

life classes and objects


Contd…
A class uses variables to define data fields and
functions to define behaviors
D/ce b/c struct & class keyword is that
classes have private members & structure have
public members by default
The variable itself is called an instance of the
class
A variable of a class type is also called an
object.
8
Objects
Class Name: Circle A class template

Data Fields:
radius is _______

Functions:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

An object has both a state and behavior.


The state defines the object, and the behavior 9
defines what the object does.
Defining a Class
Tells the compiler what member functions
and data members belongs to the class.
Keyword class followed by the class’s name.
Class body is enclosed in braces ({})
- Specifies data members and member
functions
- Access-specifier public:
- Indicates that a member function or data
member is accessible to other functions
10
and member functions of other classes.
Defining a Class
class Circle
{
public:
// The radius of this circle
double radius; Data field
// Construct a circle object
Circle()
{
radius = 1;
} Constructors

// Construct a circle object


Circle(double newRadius)
{
radius = newRadius;
}

// Return the area of this circle


double getArea() Function
{
return radius * radius * 3.14159;
11
}
};
Class Time
class Time {

Definition of class begins


public: Class body starts with left
with keyword class.
brace.
Time(); // constructor Function prototypes for
void setTime( int, int, int ); // set hour, minute,
publicsecond
member
void printUniversal();Constructor hasuniversal-time
// print same functions.
Member access specifiers.
format
name as class, Time, and
void printStandard();no return// type.
print standard-time format

private data members


private: accessible only to member
int hour; // 0 - 23 (24-hour clock format)
functions.
int minute; // 0 - 59
int second; Class
// 0 body
- 59 ends with right
Definition terminates with
brace.
semicolon.
}; // end class Time 12
Gradebook Example
1 // Fig. 19.1: fig19_01.cpp
2 // Define class GradeBook with a member function displayMessage;
3 // Create a GradeBook object and call its displayMessage function.
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 // GradeBook class definition
9 class GradeBook
10 {
11 public:
12 // function that displays a welcome message to the GradeBook user
13 void displayMessage()
14 {
15 Member function
cout << "Welcome to the Grade Book!" << endl;
16 } // end function displayMessage displayMessage returns nothing
17 }; // end class GradeBook
18
19 // function main begins program execution
20 int main()
21 {
22 GradeBook myGradeBook; // create a GradeBook object named myGradeBook
23 myGradeBook.displayMessage(); // call object's displayMessage function
24 return 0; // indicate successful termination
25 } // end main
Use dot operator to call
GradeBook’s member function 13
Welcome to the Grade Book!
Access Modifiers
Class members fall under one of three different
access permission categories:
public: members are accessible by all class
users
private: members are only accessible by the
class members
- information is hidden from “clients” outside the class
protected: members are only accessible by
the class members and the members of their
derived class.
Usually, the data members of a class are declared 14
in the private: section of the class and the member
functions are in public: section.
Scope Resolution Operator (::)
It comes in two forms
 Unary form – used to uncover or to access a
name that has external scope and has been
hidden by local or class scope.
 Binary form – places the class or namespace
identifier before the operator and the
identifier after the operator
::i // unary - refers to external scope
MyClass::x // binary - refers to class scope
15
Scope Resolution Operator (::)
Binary scope resolution is used to clarify names
that are reused within classes
For example, we need scope resolution to define
member functions:
class Student void Student::PrintName()
{ {
public: cout << studentName;
void PrintName(); }
private:
string studentName;
}; 16
Class Data
Normally member functions of a class and data
will logically belong with each object of a
class (instance members)
student s1.mark = 56;
my_car.color = red;
my_car.print();
Can also have members that are shared
between all objects of a class (class wide)
car::print_number();
student::passmark = 45; 17
Static Members
Using the modifier static when declaring a
data member means that the data member is
independent of any given class variable.
A static data member is commonly accessible
by all instances of its class; it is a global
member within class scope
It has access to only static members (functions
or variables)
It doesn’t require object
Can be accessed in the form 18

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

Since it is not const,


anyone can modify it

20
Defining Static Data Members

Static variables are sometimes called


class variables, class fields,
or class-wide because they don’t
belong to a specific object; they belong to 21

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

• Use static data members to save storage when a single


copy of the data for all objects of a class will suffice.
• A class’s static data members and static member
functions exist and can be used even if no objects of that
class have been instantiated.

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

static member function can access


only static data, because the function 28
might be called when no objects exist
22
23 // constructor dynamically allocates space for first and last name and
24 // uses strcpy to copy first and last names into the object
25 Employee::Employee( const char * const first, const char * const last )
26 {
27 firstName = new char[ strlen( first ) + 1 ];
28 strcpy( firstName, first );
29 Non-static member function
30 lastName = new char[ strlen( last ) + 1 ]; (i.e., constructor) can modify the
31 strcpy( lastName, last ); class’s static data members
32
33 count++; // increment static count of employees
34
35 cout << "Employee constructor for " << firstName
36 << ' ' << lastName << " called." << endl;
37 } // end Employee constructor
38
39 // destructor deallocates dynamically allocated memory
40 Employee::~Employee()
41 {
42 cout << "~Employee() called for " << firstName
43 << ' ' << lastName << endl;
44
45 delete [] firstName; // release memory
46 delete [] lastName; // release memory
47
48 count--; // decrement static count of employees 29
49 } // end ~Employee destructor
1 // Fig. 10.23: fig10_23.cpp
2 // Driver to test class Employee.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include "Employee.h" // Employee class definition
8
9 int main()
10 {
11 // use class name and binary scope resolution operator to
12 // access static number function getCount
13 cout << "Number of employees before instantiation of any objects is "
14 << Employee::getCount() << endl; // use class name
15 Calling static member function using class
16 // use new to dynamically create two new Employees
name and binary scope resolution operator
17 // operator new also calls the object's constructor
18 Employee *e1Ptr = new Employee( "Susan", "Baker" );
19 Employee *e2Ptr = new Employee( "Robert", "Jones" );
20
21 // call getCount on first Employee object
Dynamically creating Employees with new
22 cout << "Number of employees after objects are instantiated is "
23 << e1Ptr->getCount();
24
Calling a static member function
25 cout << "\n\nEmployee 1: "
26 << e1Ptr->getFirstName() << " " << e1Ptr->getLastName()
through a pointer to an object of the class
27 << "\nEmployee 2: "
28 << e2Ptr->getFirstName() << " " << e2Ptr->getLastName() << "\n\n";
30
29
30 delete e1Ptr; // deallocate memory
31 e1Ptr = 0; // disconnect pointer from free-store space
32 delete e2Ptr; // deallocate memory
33 e2Ptr = 0; // disconnect pointer from free-store space
34
35 // no objects exist, so call static member function getCount again
36 // using the class name and the binary scope resolution operator
37 cout << "Number of employees after objects are deleted is "
38 << Employee::getCount() << endl;
39 return 0;
40 } // end main

Number of employees before instantiation of any objects is 0


Employee constructor for Susan Baker called.
Employee constructor for Robert Jones called.
Number of employees after objects are instantiated is 2

Employee 1: Susan Baker


Employee 2: Robert Jones

~Employee() called for Susan Baker


~Employee() called for Robert Jones
Number of employees after objects are deleted is 0

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;

 constructs a new car, c2 “default constructor” with


initial position set to 0,0
car c3();

 defines a new function, c3 accepting no


parameters and returning a car object! 50
Object Names
In C++, you can assign a name when
creating an object
A constructor is invoked when an object is
created.
The syntax to create an object using the no-
arg constructor is
ClassName variableName;
For example,
Circle circle1; 51
Constructing with Arguments
The syntax to declare an object using a
constructor with arguments is
ClassName variableName (arguments);
For example, the ff declaration creates an
object named circle2 by invoking the
Circle class’s constructor with a specified
radius 5.5
Circle circle2(5.5);
52
Access Operator
After an object is created, its data can be
accessed and its functions invoked using
the dot operator (.), also known as the
object member access operator:
objectName.dataField references data
field in the object
invokes an function on the object
objectName.function(arguments)
53
references data field in the object
Ways to make new objects
• Declaring them as a new local or global object,
car c1(5,5);
• constructor is called
• Declaring them as a copy of another object,
car c2 = c1;
• copy constructor is called
• Dynamically,
car* c3 = new car;
• constructor is called

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

Вам также может понравиться