Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes.

Similar presentations


Presentation on theme: "Classes."— Presentation transcript:

1 Classes

2 Warmup class Thing { public: void foo(int a) {cout << “A”;}
void foo(double a) {cout << “B”;} }; int main() Thing a(); a.foo(1); } What will this script output?

3 Warmup 2 void foo() { cout << “B”; } class Thing { public:
void foo() {cout << “A”;} void bar() {foo();} }; int main() Thing a(); a.bar(); What will this script output?

4 Header Files In order to promote reusability of code, it is common to put user-defined classes and functions into header files. This way if another person wants to reuse classes or functions, they can simply include the header file. This is done using #include “filename.h” which pastes the contents of the file filename.h into a program

5 Separating Interface and Implementation
It is also common to put declarations into a .h file and put the associated definitions into .cpp file of the same name. If we define a Person class, we would be the declarations into a person.h file and the definitions into a person.cpp file. We would include person.h in our person.cpp file

6 Header Files Always put #pragma once at the beginning of a header file. Otherwise, if multiple files include the header file in a project, there are redefinition problems. Alternatively can put #ifndef FILENAME_H #define FILENAME_H at the start and #endif at the end

7 Problem: Implementing a Date class
Suppose we wanted to implement a class which represents dates, e.g., 10/23/1997. Things to consider when designing this class: What data variables would we want an object of this class to have? What methods should an object of this class have?

8 Problem: Date Class Implement a Date class which has 3 data variables (day, month, year) and the following methods A constructor that accepts three input variables (corresponding to the month, day, and year) A default constructor that accepts no input variables and sets the date to 1/1/1970 One accessor function for each of our private data variables. A mutator function that inputs three variables (corresponding to the day, month, and year) and sets the stored date equal to that input. A procedure that prints the stored date to the console in the format MM/DD/YYYY.

9 Problem: Equality Testing
Write a method for Date equals which accepts a Date object and returns true if they are equal. Date date1(1,6,1999), date2(1,7,1999); date1.equals(date2) // should be false What should the header of the method look like? What should be in the body? Why can’t we just do date1 == date2?

10 Operator Overloading: ==
We can define == for our Date class. bool Date::operator==(const Date &date) const { return equals(date); }


Download ppt "Classes."

Similar presentations


Ads by Google