CS 202 Fall 2013 > Notes for Tuesday, September 24, 2013 |
CS 202 Fall 2013
Notes for Tuesday, September 24, 2013
Classes II: Some Details [14.1–14.3]
Terminology
- Local
- Declared inside a function.
- Member
- Declared inside a class.
- Global
- Neither.
Assignment
A C++ compiler will write an assignment operator
(“=
”)
for a class
as long as you do not declare one
(we do not know how to do declare one, yet).
This operator will do assignment on each member variable.
[C++]
class Ggg { private: int _x; double _y; string _z; }; Ggg a; Ggg b; a = b;
The assignment above (“a = b;
”)
is essentially the same as
[C++]
a._x = b._x; a._y = b._y; a._z = b._z;
except that these would not compile, since the member variables are private.
Static Member Variables
If a member variable is declared static
,
then there is only one copy of it
(as opposed to a separate copy for each object).
[C++]
class Hhh { private: int _x; static double _y; };
When defining a class in separate header/source files,
initialize a static
member variable
in the source file.
[C++]
// hhh.cpp #include "hhh.h" double Hhh::_y = 7.1;
Since a static
member variable
is not part of an object,
it can be modified in a const
member function.
[C++]
class Hhh { public: void foo() const { _y = 3.2; } private: static double _y; };
Static Member Functions
Member functions can also be static
.
Such a function does not need to be called
on a particular object.
Note that a static
member function
cannot be const
.
[C++]
class Iii { public: static void bar() { ... } };
We can call a static
member function
using an object.
[C++]
Iii x; x.bar();
Or call it using the class name and “::
”.
[C++]
Iii::bar();
Global Functions in a Package
To put a global function into the same package as a class, prototype it in the header, and define it in the source.
[C++]
// xyz.h #ifndef XYZ_H #define XYZ_H class Xyz { ... }; void foo(); #endif //#ifndef XYZ_H
[C++]
// xyz.cpp #include "xyz.h" void foo() { blah_blah_blah(); }
Friend Functions
A global function can access private members of a class
if it is a friend of the class.
Make a function a friend by putting a prototype
of the function inside the class definition,
preceded by
“friend
”.
Note that a friend will generally end up having two prototypes.
[C++]
// xyz.h #ifndef XYZ_H #define XYZ_H class Xyz { friend void foo(); ... }; void foo(); #endif //#ifndef XYZ_H
Example Code
See
sumup.h
and
sumup.cpp
for the code for class SumUp
,
which, among other things,
has a static
data member
and a friend
.
See
dosumup.cpp
for a C++ program that uses class SumUp
.
For today’s lab work, see the 9/24 Challenge.