CS11 Lecture Notes - Object Oriented Programming: Intro
2 questions when approaching a problem:
Q: how to represent and structure the data?
A: Data Structures
Q: how to perform computation on the data?
A: Functions
Object-Oriented Programming (OOP)
- a way of thinking about programming and a new way to think about code
- OOP is a “programming paradigm”
- C++ provides OOP features
Classes and Object (Conceptually)
● a class is a blueprint
1. describes the components of a “thing” (like a struct type)
2. Outlines how to interact with that thing (like functions operating on a struct)
● an object is an “instance” that a class
1. has specific values for each component
2. objects are independent of one another: interacting with one object doesn’t affect others
Class Definition in C++
● can also bundle functions into a class
○ we call the functions associated with a class the member functions or methods.
Objects in C++
● also need to call the member function in the main function for a specific object. (like
which dog)
string and ifstream are classes. ex. infile.open(); and word.length();
Defining a Class Method
● :: is the “scope resolution operator”
○ it associates the function with a class making it a method
○ the method can access any class members without needing the usual dot
operator
Exercise: OOP Basics
1. class definition for Fruit
class Fruit {
public:
bool is_rotten;
string variety;
int days;
float price;
}
2. method definition for is_rotten
bool is_rotten() {
if (days > 2) {
return true;
} else {
return false;
}
}
Encapsulation with Public vs Private
● a private class member can only be used by that class’ methods
● Encapsulation: restricting outside access to some of a class’ members
●