Classes
Week 3
A class is a new type
Interface:
Example: a Pair class
Pair class
Example: a Pair class
How to hide the contents of an object so that outside code cannot manipulate it directly?
For functions that users of the class should call:
public: and private: are called access modifiers.
class XYZ {
public:
void copyXTo(XYZ other) {
other.x = x; // legal?
}
private:
int x;
};
In the class XYZ, x is private.
Will the line "other.x = x;" compile?
Test-driven Development
TDD: philosophy of software development.
Pair implementation
Using tests.cpp/catch.hpp as the testing framework.
#include <string>
using namespace std;
typedef int Item;
class Pair {
public:
// default constructor
Pair();
// explicit-value constructor
Pair(Item first, Item second);
// getters
Item getFirst() const;
Item getSecond() const;
// setters
void setFirst(Item newVal);
void setSecond(Item newVal);
string toString() const;
private:
Item myFirst;
Item mySecond;
};
ostream &operator<<(ostream &out, const Pair &p);
/**
* @brief return a string with the format <myFirst, mySecond>.
*
* @return string
*/
string Pair::toString() const {
return "<" + to_string(myFirst) + ", " + to_string(mySecond) + ">";
}
ostream &operator<<(ostream &out, const Pair &p) {
out << p.toString();
return out;
}
main…
assert(p2.toString() == "<1, 2>");
cout << p2 << endl;
cout << "Check that above output is <1, 2>\n";
Pair p3 = testReturnPair(7, 10);
assert(p3.toString() == "<7, 10>");
cout << "All tests passed!\n";
Create an Enemy class
Enemy class
Rectangle Class
With neighbor, define the class.
What data?
What operations?
What tests?
Exercise: practice for loop
Suppose we have an array, numbers, of size 8, containing integers.
Write code to declare a second array, n2, of size 8, and copy the 8 integers from numbers into n2.
Exercise: practice for loop
Suppose we have an array, numbers, of size 20, containing integers.
Write code to move all the values "down" in the same array.
(The top value (at index 19) is left as it is. The 0th value is "lost".)
Exercise: practice for loop
Suppose we have an array, numbers, of size 8, containing integers.
Write code to create a second array, reversed, and copy the 8 integers from numbers into reversed, in reverse order.