Introduction to classes
Motivating example
What exactly is a class?
structs vs. classes
class structure
Writing our first class
Activity: Rectangle class implementation
Graded Playground Autograder
In this activity, you will implement a Rectangle
class. The Rectangle
class should accept two double
s, width
and height
that it should maintain as private
member variables, with the preserved invariant being that both side lengths must be greater than 0
. If at any point this invariant is violated, throw an std::invalid_argument
exception. The class should support two public
and const
member functions Width
and Height
that access the respective side lengths. The class should also support two public
and void
member functions Width
and Height
that accept a double
argument and mutate the respective private
member variables. Lastly, the class should support a const
public member function Area
that computes and returns the area of the object.
Function | Description |
---|---|
Rectangle(double width, double height) |
Constructor. |
double Area() const |
Returns area of object. |
void Width(double w) |
Setter for width_ . |
void Height(double h) |
Setter for height_ . |
double Width() const |
Getter for width_ . |
double Height() const |
Getter for height_ . |
Data Member | Description |
---|---|
double width_ |
Width of object. |
double height_ |
Height of object. |
Note: We haven't talked about constructors, but they are called at the point of declaration to build an object of a user-defined type. These are special functions that do not specify a return type and are named the same as the class. We will introduce constructors in more detail tomorrow.
Your Rectangle
type will specify a parameterized constructor. This means you cannot build a Rectangle
object with the following statement: Rectangle r;
. That will not work. Instead, you must build a Rectangle
object by providing the parameterized constructor arguments for its width and height: Rectangle r(1,2);
. The declaration of the parameterized constructor will be written as follows inside the class definition:
Rectangle(double width, double height);
The definition of the parameterized constructor will use a fully qualified name to specify that we are defining a function within the scope of Rectangle
:
Rectangle::Rectangle(double width, double height) : width_(width), height_(height) {
// ... Check whether width_ and height_ have taken on valid values.
}
The colon (:
) following the parameter list and before the open-brace {
is called the initializer list. Using the initializer list, we have initialized the private data members with the function's arguments for you. All you must do is check whether each data member's value is valid inside the function's body. This should be enough to get you started.