Beruflich Dokumente
Kultur Dokumente
Classes
COS110: Chapter 14
Dr. Mard Helbig
Instances
Each instance of a class has its own copies of the
classs variables
class Wizard
{
private:
string name;
string school;
public:
Wizard();
~Wizard();
void setName(string);
void setSchool(string);
double getName() const;
double getSchool() const;
};
In main.cpp:
Wizard wizard1;
harry.setName(Harry);
harry.setSchool(Griffendor);
Wizard wizard2;
Malfoy.setName(Malfoy);
Malfoy.setSchool(Slitheren);
wizard1 object
wizard2 object
name
Harry
name
Malfoy
school
Griffendor
school
Slitheren
Instances
Member variables of a class is called instance
variables each instance of class has its own copies
class Wizard
{
private:
string name;
string school;
public:
Wizard();
~Wizard();
void setName(string);
void setSchool(string);
double getName() const;
double getSchool() const;
};
Instance variables
wizard1 object
wizard2 object
name
Harry
name
Malfoy
school
Griffendor
school
Slitheren
Static members
Can create a member variable or member function
that does not belong to an instance of a class
=> the class has only one copy of the member
Known as static member variables or static member
functions
When storing a value in a static variable, it is not store
in an instance of the class
An instance of class does not have access to a static
member variable
Static member functions can only operate on static
member variables
Static members
Think of normal private class variables as gholf balls
Each instance of class (GholfPlayer) has its own ball
that s/he is playing with
Wizard.h
Wizard.cpp
Wizard.h
Wizard.cpp
No static keyword!
Friends of a class
Private members of a class cannot be accessed from
outside the class, except through public member
functions
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
A friend is treated like a member of the class
Define it as follows:
friend returnType functionName (ParameterListType)
Wizard.h
Wizard.cpp
Dwarf.h
Dwarf.cpp
Friends of a class
class Wizard
{
private:
string name;
string school;
static int acceptedInvites;
static int maxAcceptance;
public:
Wizard();
~Wizard();
void setName(string);
void setSchool(string);
string getName() const;
string getSchool() const;
void acceptInvite(bool);
static void wizardInvites(int);
static int numAcceptedInvites();
friend void Dwarf::acceptInvite(bool,
&Wizard);
};
Friends of a class
class Wizard;
class Dwarf
{
private:
string name;
public:
Dwarf();
Dwarf(string);
void setName(string);
string getName() const;
void acceptInvite(bool, &Wizard);
};
Forward declaration of
class Wizard
Friends of a class
void Dwarf::acceptInvite(bool ans, &Wizard wiz)
{
if (ans)
if (wiz.acceptedInvites <
wiz.maxAcceptance)
wiz.acceptedInvites++;
};
Definition of friend
function in Dwarf.cpp