Lecture 19: More Classes

Mar 20, 2024  β”‚  Last updated Mar 22, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Intro to object oriented programming
  • Abstraction terminology
  • Classes and objects - defining, creating, using

Textbook Sections 10.2-10.3

class Cat {
public:
    void meow();
private:
    string name;
    int age;
};

Today’s topics

Textbook Sections 10.2, 11.2

Our Time class

const correctness

How should I ensure that these functions don’t modify the Time object?

void write(std::ostream &out);
int compare(Time other);

For that matter we might want to make compare take a const Time & instead of a Time - why?

Remember this?

const correctness

Let’s go ensure const correctness in our Time class

Constructors

Implementing a constructor

Using a constructor

Side tangent: Function overloading

Side tangent: Function signatures

What counts as a different signature? Consider void foo(int a, int b);:

FunctionDifferent?
void foo(int a, int b, int c);Yes - number of parameters
void foo(int a, char c);Yes - types of parameters
void foo(char c, int a);Yes - order of parameters
void foo(int c, int d);No - names of parameters don’t matter
void foo(const int a, int b);No - const doesn’t matter
bool foo(int a, int b);No - return type doesn’t matter

Back to constructors

Destructors

Using a destructor

Better example: An IntList class

class IntList {
public:
    IntList();
    ~IntList();
    void append(int n);
    void write(std::ostream &out) const;
private:
    struct Node {
        int data;
        Node *next;
    };
    Node *head;
};

The IntList destructor

IntList::~IntList() {
    Node *curr = head;
    while (curr) {
        Node *temp = curr;
        curr = curr->next;
        delete temp;
    }
}

emoji const and Constructors check-in 1/2

Which of the following is not a valid constructor declaration for the Time class?

  1. Time();
  2. Time(int h, int m, int s);
  3. Time(int h, int m);
  4. Time(int h, int m, int s) const;
  5. Time(std::string the_time);

emoji const and Constructors check-in 2/2

const after a member function declaration means:

  1. The function can only be called on const objects
  2. The this pointer is const, but the object it points to is not
  3. The object the this pointer points to is const, but the pointer itself is not
  4. The function will not modify the object it is called on
  5. The function will not modify the arguments that are passed to it

Operator overloading

Operator overloading

Coming up next



Previous: Lecture 18: Intro to Classes
Next: Lecture 20: ADT Case study