Download Notes on C++ Classes - Data Structures | CSCI 1200 and more Study notes Data Structures and Algorithms in PDF only on Docsity!
CSCI-1200 Computer Science II — Fall 2007
Lecture 3 — Classes I
Review from Lecture 2
- Vectors are dynamically-sized arrays
- Vectors, strings and other containers should be:
- passed by reference when they are to be changed, and
- passed by constant reference when they aren’t.
If you forget the & and pass by value, the object will be copied which is expensive for containers with lots of elements. Note: This is unlike arrays, which are not copied when passed by value.
- Vectors can “contain” any type of objects, including strings and other vectors.
Today’s Lecture: C++ classes
- Types and defining new types
- A Date class.
- Class declaration: member variables and member functions
- Using the class member functions
- Class scope
- Member function implementation
- Classes vs. structs
- Designing classes
3.1 Types and Defining New Types
- What is a type? It is a structuring of memory plus a set of operations (functions) that can be applied to that structured memory.
- Examples: integers, doubles, strings, and vectors.
- In many cases, when we are using a class we don’t know how that memory is structured. Instead, what we really think about is the set of operations (functions) that can be applied.
- To clarify, let’s focus on strings and vectors. These are classes. We’ll outline what we know about them:
- The structure of memory within each class object
- The set of operations defined
- We are now ready to start defining our own new types using classes.
3.2 Example: A Date Class
- Many programs require information about dates.
- Information stored about the date includes the month, the day and the year.
- Operations on the date include recording it, printing it, asking if two dates are equal, flipping over to the next day (incrementing), etc.
3.3 C++ Classes
- A C++ class consists of
- a collection of member variables, usually private, and
- a collection of member functions, usually public, which operate on these variables.
- public member functions can be accessed directly from outside the class,
- private member functions and member variables can only be accessed indirectly, through public member functions.
- We will look at the example of the Date class declaration.
3.4 Using C++ classes
- We have been using C++ classes (from the standard library) already this semester, so studying how the Date class is used is simply a review:
// Program: date_main.cpp // Purpose: Demonstrate use of the Date class.
#include #include "date.h"
int main() { std::cout << "Please enter today’s date.\n" << "Provide the month, day and year: "; int month, day, year; std::cin >> month >> day >> year; Date today(month, day, year);
Date tomorrow(today.getMonth(), today.getDay(), today.getYear()); tomorrow.increment();
std::cout << "Tomorow is "; tomorrow.print(); std::cout << std::endl;
Date Sallys_Birthday(9,29,1995); if (sameDay(tomorrow, Sallys_Birthday)) { std::cout << "Hey, tomorrow is Sally’s birthday!\n"; }
std::cout << "The last day in this month is " << today.lastDayInMonth() << std::endl; return 0; }
- Important: Each object we create of type Date has its own distinct member variables.
- Calling class member functions for class objects uses the “dot” notation. For example, tomorrow.increment();
- Note: We don’t need to know the implementation details of the class member functions in order to understand this example. This is an important feature of object oriented programming and class design.
3.5 Exercise
Add code to date_main.cpp to read in another date, check if it is a leap-year, and check if it is equal to tomorrow. Output appropriate messages based on the results of the checks.
int Date::getDay() const { return day; }
int Date::getMonth() const { return month; }
int Date::getYear() const { return year; }
void Date::setDay(int d) { day = d; }
void Date::setMonth(int m) { month = m; }
void Date::setYear(int y) { year = y; }
void Date::increment() { if (!isLastDayInMonth()) { day++; } else { day = 1; if (month == 12) { // December month = 1; year++; } else { month++; } } }
bool Date::isEqual(const Date& date2) const { date2.getDay(); return day == date2.day && month == date2.month && year == date2.year; }
bool Date::isLeapYear() const { return (year%4 ==0 && year % 100 != 0) || year%400 == 0; }
int Date::lastDayInMonth() const { if (month == 2 && isLeapYear()) return 29; else return DaysInMonth[ month ]; }
bool Date::isLastDayInMonth() const { return day == lastDayInMonth(); // uses member function }
void Date::print() const { std::cout << month << "/" << day << "/" << year; }
bool sameDay(const Date& date1, const Date& date2) { return date1.getDay() == date2.getDay() && date1.getMonth() == date2.getMonth(); }
3.7 Class scope notation
- Date:: indicates that what follows is within the scope of the class.
- Within class scope, the member functions and member variables are accessible without the name of the object.
3.8 Constructors
These are special functions that initialize the values of the member variables. You have already used constructors for string and vector objects.
- The syntax of the call to the constructor mixes variable definitions and function calls. (See date main.cpp)
- “Default constructors” have no arguments.
- Multiple constructors are allowed, just like multiple functions with the same name are allowed. The compiler determines which one to call based on the types of the arguments (just like any other function call).
- When a new object is created, EXACTLY one constructor for the object is called.
3.9 Member Functions
Member functions are like ordinary functions except:
- They can access and modify the object’s member variables.
- They can call the other member functions without using an object name.
- Their syntax is slightly different because they are defined within class scope.
For the Date class:
- The set and get functions access and change a day, month or year.
- The increment member function uses another member function, isLastDayInMonth.
- isEqual accepts a second Date object and then accesses its values directly using the dot notation. Since we are inside class Date scope, this is allowed. The name of the second object, date2, is required to indicate that we are interested in its member variables.
- lastDayInMonth uses the const array defined at the start of the .cpp file.
More on member functions:
- When the member variables are private, the only means of accessing them and changing them from outside the class is through member functions.
- If member variables are made public, they can be accessed directly. This is usually considered bad style and is not be allowed in this course.
- Functions that are not members of the Date class must interact with Date objects through the class public members (a.k.a., the “public interface” declared for the class). One example is the function sameDay which accepts two Date objects and compares them by accessing their day and month values through their public member functions.
3.10 Header Files (.h) and Implementation Files (.cpp)
The code for the Date example is in three files:
- The header file, date.h, contains the class declaration.
- The implementation file, date.cpp, contains the member function definitions. Note that date.h is #include’ed.
- date main.cpp contains the code outside the class. Again date.h again is #include’ed.
- The files date.cpp and date main.cpp are compiled separately and then linked to form the executable program.
- Different organizations of the code are possible, but not preferable. In fact, we could have put all of the code from the 3 files into a single file main.cpp. In this case, we would not have to compile two separate files.
- In many large projects, programmers establish follow a convention with two files per class, one header file and one implementation file. This makes the code more manageable.