CS 202 Fall 2013 > Notes for Tuesday, September 17, 2013 |
CS 202 Fall 2013
Notes for Tuesday, September 17, 2013
Classes I Day 3 [13.11–13.12]
Private Member Functions
Member functions can be made either public
or private
.
Why would you want a private
member function?
Usually, such a function is an internal-use utility function
that simplifies the implementation of the class.
Consider the following class.
[C++]
class Bar { public: void f1() const { for (int i = 0; i < 10; ++i) { cout << "ho" << endl; } } void f2() const { for (int i = 0; i < 20; ++i) { cout << "hi" << endl; } } void f3() const { for (int i = 0; i < 30; ++i) { cout << "hey" << endl; } } };
The three member functions above are very similar.
We might want to write a helper function that
they all use.
If we do not want the outside world to have access to this
new functionality,
then we would make the helper function private
.
[C++]
class Bar { public: void f1() const { printRepeat("ho", 10); } void f2() const { printRepeat("hi", 20); } void f3() const { printRepeat("hey", 30); } private: void printRepeat(string msg, int num) const { for (int i = 0; i < num; ++i) { cout << msg << endl; } } };
Objects in a Container
We can put objects in a container
(for example, a vector
or an array)
just like any other type.
To start things off, here is a class.
[C++]
class Bar { ... };
To make a vector
of Bar
objects,
we could do something like this.
[C++]
vector<Bar> v; Bar f; v.push_back(f); // And so on
Creating a container with a given size allows us to construct a large number of objects at once. However, we have little freedom regarding the parameters we pass to the objects’ constructors.
[C++]
vector<Bar> w(1000);
All 1000 objects above will be default-constructed.
So we cannot make such a container unless class Bar
has a default constructor.
(Recall that a class’s default constructor is written for you
as long as you declare no constructor.
Otherwise—if you want to have a default constructor—you
must write one yourself.)
Example Code
See
fancyprint.h
and
fancyprint.cpp
for the code for class FancyPrint
,
which, among other things,
has a private member function.
See
dofancyprinting.cpp
for a C++ program that uses class FancyPrint
.
This program makes a container holding several objects.
For today’s lab work, see the 9/17 Challenge.