Upload
mohamed-shehab
View
223
Download
0
Embed Size (px)
Citation preview
8/2/2019 Windows-1256 Classes
1/36
8/2/2019 Windows-1256 Classes
2/36
What Are Classes?
asses ex en e u - n capa es o ++ o ass s youin representing and solving complex, real-world problems.
ou ma e a new ype y ec ar ng a c ass. c ass s us a
collection of variables combined with a set of related.
A class can consist of any combination of the variable types
.
referred to as the member variables or data members. The
variables. They are referred to as member functions or
methods of the class.
A class enables you to encapsulate these variables and
functions into one collection which is called anob ect.
8/2/2019 Windows-1256 Classes
3/36
Declaring a Class
o ec are a c ass, use e class eywor o owe y anopening brace, and then list the data members and methods of
.
semicolon.
.
class ClassName
memberList
Here ClassNameis the name of the class, andmemberList is
.
8/2/2019 Windows-1256 Classes
4/36
memberList consists of a list of member declarations. These
.Data member declarations are normal variable declarations.
, n x
a class. However, you cannot initialize data members where
.
or outside the class. For example, int x = 50; as a data
.
Method declarations are function declarations placed inside a
implementation, or you can implement it separately). All
8/2/2019 Windows-1256 Classes
5/36
Example:
{
intmodelnumber;
double cost;
void SetPart(intmn, double c);
void ShowPart
};
Anobject is an individual instance of a class. You define an
variable (or any other variable):
ar w ee ;
This code defines wheel, which is an object whose class (or
ype s Part.
8/2/2019 Windows-1256 Classes
6/36
Calling Data Member and Member Functions
nce you e ne an ac ua Part o ec - or examp e, wheel-you use the dot operator (.) to access the members of that
o ec .
Therefore, to assign 50 to wheels modelnumber membervar a e, you wou wr e
wheel.modelnumber = 50;
In the same way, to call the ShowPart() function, you wouldwrite
wheel.ShowPart();
When you use a class method, you call the method. In thisexample, you are calling ShowPart() on wheel.
8/2/2019 Windows-1256 Classes
7/36
Assign Values to Objects, Not to Classes
In C++ you don't assign values to types; you assign values tovariables. For example, you would never write
int = 50; //wrong
The compiler would flag this as an error, because you can't
assign 50 to an integer. Rather, you must define an integer
variable and assign 50 to that variable. For example,
int x; //define x to be an int
x = 50; //set x's value to 50
This is a shorthand way of saying, "Assign 50 to the variable
x, which is of type int".
8/2/2019 Windows-1256 Classes
8/36
In the same way, you wouldn't write
Part.modelnumber = 50; wrong ???
The compiler would flag this as an error, because you can't
assign 50 to themodelnumber of a Part. Rather, you must
define a Part object and assign 50 to themodelnumber ofa o ec .
For example:
Part wheel; //just like int x;wheel.modelnumber = 50; //just like x = 50;
8/2/2019 Windows-1256 Classes
9/36
Using Access Specifiers
++ a ows you o con ro w ere e a a mem ers o yourclass can be accessed. This control is a powerful tool because it
.
specifier is a word that controls where the data members in a
class can be accessed. The s ntax for an access s ecifier is as
follows:
class ClassName
{classMembers;
classMembers;
};An access specifier affects all members of the class (including
methods) that come after it until another access specifier is
encountered or until you reach the end of the class.
8/2/2019 Windows-1256 Classes
10/36
A class has two kinds of access specifiers:public andprivate.
the class can be accessed and from within the class (that is, in
the classs methods).
private members can be accessed only from within the class
itself. An object of the class cannot access the private, .
specifier is provided in the class, all members default to
private.
Here is an example of how you might use these specifiers:class ClassName{
int x;
public:int y;int z;
rivate:int a;
};
8/2/2019 Windows-1256 Classes
11/36
In this example, x and a are private members, and y and z are
.your classes.
8/2/2019 Windows-1256 Classes
12/36
Class Members Are Private by Default
n e class Part ec ara on examp emodelnumber, cost,SetPart(), and ShowPart() are all private, because all
.
unless you specify otherwise, they are private. Therefor, if you
Part wheel;
wheel.modelnumber = 50; //error
the compiler flags this as an error, becausemodelnumber is
rivate and ou can't access rivate data.
The way to use wheel so that you can access the data
members is to declare it ublic.
8/2/2019 Windows-1256 Classes
13/36
class Part
public:intmodelnumber;
ou e cos ;
void SetPart(intmn, double c);
void ShowPart();};
Nowmodelnumber cost SetPart() and ShowPart() are
allpublic. And wheel.modelnumber = 50; compiles withoutproblems.
8/2/2019 Windows-1256 Classes
14/36
Private and Public Data
arepublic. This is a result of how classes are used. The data
i hidden o it will be afe from accidental mani ulation
while the functions that operate on the data are public so
they can be accessed from outside the class. However, thereis no rule that data must be private and functions public; in
some circumstances you may find youll need to use private
functions and public data.class Part
private:
intmodelnumberdouble cost;
public:
vo e ar n mn, ou e c ;
};
8/2/2019 Windows-1256 Classes
15/36
#include
class Part
{private:
double cost;
public:void SetPart(intmn, double c) //set data
{
modelnumber = mn
cost = c;}
{
cout
8/2/2019 Windows-1256 Classes
16/36
intmain()
Part part1, part2, part3;
part1.SetPart(6245, 220);
part .SetPart , ;
part3.SetPart(6247, 150);
art1.ShowPart
part2.ShowPart();
part3.ShowPart();
re urn ;
}
Output:
,
Model 6246, costs $185
Model 6247, costs $150
8/2/2019 Windows-1256 Classes
17/36
Memory Allocation
' ar .just tells the compiler what a Part is, what data it contains
modelnumber and cost and what it can do SetPart
and ShowPart()). It also tells the compiler how big a Part
is (that is, how much room the compiler must set aside foreach Part that you create). In short, specifying a basic type
does two things:
It determines how much memory is needed for a data object. It determines what operations, or methods, can be performed
.
Each new object you create contains storage for its own
, .same class share the same set of class methods, with just one
copy of each method.
8/2/2019 Windows-1256 Classes
18/36
Creating Methods
ac unc on a you ec are or your c ass mus ave adefinition. The definition is also called the function
. ,
class method has a function header and a function body.
.
is to declare a method inside the class declaration and then
implement the method at the same time inside the classdeclaration.
You should declare most of your methods the first way.
However, there is special syntax for the method definition. Amember function definition begins with the return type,
followed by the name of the class, two colons (::), the name
of the function, and its parameters.
8/2/2019 Windows-1256 Classes
19/36
Here is the general syntax for a method implementation that
return_typ ClassName::methodName(parameterList)
methodImplementation;
Here ClassName is the name of the class, and
methodImplementationis the code that goes inside themethod. As you can see, this syntax is very similar to the
unc on e n on syn ax. e ou e co on :: s ca e
the scope resolution operator. Here you are telling the
in front.
8/2/2019 Windows-1256 Classes
20/36
Constructor and Destructor
,
destructor, can be in a class. Both are optional, but they
rovide s ecial functionalit that other methods cannot
provide.
A constructor is executed every time a new instance of theclass is created -that is, every time you declare a new object-.
The constructor is normally used to set initial values for the
data members. A constructor always has the same name as
the class and cannot have a return value (not evenvoid).
es ruc or s e oppos e o a cons ruc or an s execu e
when the object is destroyed. The destructor is always named
~,beginning. The destructor cannot have arguments or a
return value. A destructor is often used to perform any
necessary cleanup tasks.
8/2/2019 Windows-1256 Classes
21/36
Both constructors and destructors are like methods; they
declared and implemented separately. Here is the syntax for
declaring and implementing at the same time:
class ClassName
{constructor
ClassName([argumentList])
{
implementation;}
~ClassName()
{
mp emen a on;
}
//other members
};
8/2/2019 Windows-1256 Classes
22/36
Here is the syntax for declaring and then implementing:
c ass ass ame{
ClassName([argumentList]);
~ClassName();
//other Members
ClassName::ClassName([argumentList])
implementation;}
ClassName::~ClassName()
implementation;
}
8/2/2019 Windows-1256 Classes
23/36
Notice that the constructor can have arguments. If you
must supply values for these arguments when creating an
object.
The destructor, on the other hand, cannot have arguments. It
is called automatically, so there isnt necessarily a chancefor the user to provide arguments.
Because a constructor can have arguments, it might become
necessary to overload the constructor. This is legal in C++and is quite common in large classes. Overloading the
constructor in this way gives your class versatility and
provides users of the class with many options.
The destructor cannot be overloaded. Having no return type
or arguments, there is nothing with which the destructor
can be overloaded.
8/2/2019 Windows-1256 Classes
24/36
// Example 1: constructor without parameters
#include
class Part{
intmodelnumber, quantity;
double cost;pu c:
Part() //constructor no parameters
{
quantity = 100;}
~Part destructor
void SetPart(intmn, double c)
{
cost = c;
}
8/2/2019 Windows-1256 Classes
25/36
void ShowPart(){
cout
8/2/2019 Windows-1256 Classes
26/36
// Example 2: constructor with parameters
#include
class Part{
intmodelnumber, quantity;
double cost;pu c:
Part(int q) //constructor with parameter
{
quantity = q;}
~Part destructor
void SetPart(intmn, double c)
{
cost = c;
}
8/2/2019 Windows-1256 Classes
27/36
void ShowPart(){
cout
8/2/2019 Windows-1256 Classes
28/36
// Example 3: constructor with overloading#include c ass ar{private:
n mo e num er, quan y;double cost;
public:Part constructor no parameters{quantity = 100;
}Part(int q) //constructor with parameter{quantity = q;
}
~Part(){} //destructorvoid SetPart(intmn, double c){modelnumber = mn;cost = c;
}
8/2/2019 Windows-1256 Classes
29/36
void ShowPart(){
cout
8/2/2019 Windows-1256 Classes
30/36
Separating Classes into Files
,
file can quickly become unmanageable. Also, if you want to
reuse our classes in other ro rams ou have to co and
paste them into the new program.
Fortunately, there is a convention for separating classes intofiles. Normally, the class declaration is placed in one file
(header file), and the implementation of all the methods is
put in another file. The class declaration file is normally
called ClassName.h, where ClassName is the name of the
.
ClassName.cpp. Then you include the header file in your
ro ram with an #include directive.The syntax for the #include directive is as follows:
include "filename"
8/2/2019 Windows-1256 Classes
31/36
However, instead of including two files (ClassName.h and
. , . .
compiler will include the .cpp file automatically (provided
that the two file are in the ame director .
Here is how the Part class looks separated into different
//Part.hclass Part{private:
intmodelnumber, quantity;double cost;
public:
Part int~Part();void SetPart(intmn, double c);
};
//
8/2/2019 Windows-1256 Classes
32/36
//Part.cpp#include
nc u e ar .
Part::Part(int q)
quantity = q;
}Part::~Part{}void Part::SetPart(intmn, double c)
{modelnumber = mn;cost = c;
}
void Part::ShowPart(){cout
8/2/2019 Windows-1256 Classes
33/36
// Main.cpp
#include "Part.h"
intmain()
Part part1(150), part2(200);
part1.SetPart(6245, 220);part2.SetPart(6246, 185);
part1.ShowPart();
.
return 0;}
Output:
Model 6245, quantity 150, costs $220
Model 6246, quantity 200, costs $185
P i T Obj
8/2/2019 Windows-1256 Classes
34/36
Pointers To Objects
other object. You can assign this address to a suitable
Example:
" ", , , .
Account *ptrAccount = &savings;
ptrAccount. The pointerptrAccount is initialized so that itpoints to the object savings. This makes *ptrAccount the
object savings itself. You can then use the statement
(*ptrAccount).display();to call the method display() for the object savings.
Parentheses must be used in this case, as the operator . has
higher precedence than the * operator.
A O t
8/2/2019 Windows-1256 Classes
35/36
Arrow Operator
-
arrow operator) instead of a combination of* and . .
objectPointer->member
(*objectPointer).member
e opera or -> s ma e up o a m nus s gn an e grea er
than sign.
ptrAccount->display();
sp ay
referenced byptrAccount, that is, for the object savings.
The tatement i e uivalent to the tatement in the reviou
example.
Th diff b t th l b t
8/2/2019 Windows-1256 Classes
36/36
The difference between the class member access operators
->
be an object, whereas the left operand of the arrow operator
must be a pointer to an object.