Lec12 Oop
Lec12 Oop
Fundamental Computing
with C++
Object-Oriented Programming
(OOP)
Fall, 2024
Questions to Answer…
• What are classes, objects, member functions, and
data members?
• How to define a class and create an object?
• How to ask an object to perform an operation?
• What is a constructor?
• How to engineer a class with its interface to
encourage code reuse?
• How to use objects with pointers and arrays?
(Optional)
2
Objects
• Reusable software components that model real
world items
• Objects are all around you
• People, balls, cars, telephones, microwave ovens, etc.
• Objects have attributes
• Size, shape, color, weight, etc.
• Objects exhibit behaviors
• A ball can roll, bounce, inflate, deflate, …
• A baby can cry, crawl, sleep, yawn, …
• A car can accelerate, brake, turn, …
3
Object-Oriented Design
• Models real-world objects in software
“Decrease
your balance
by $300”
4
Object-Oriented Programming
(OOP)
• Programming in object oriented languages is called
object-oriented programming (OOP)
5
Classes and Objects
• Classes are blueprints to create objects
class objects
6
Class
• A class contains some data and a set of functions
that manipulate those data
7
Case Study
• Dr. Law teaches many courses
8
Defining a Class with Member
Function Beginning of
Beginning of class body
1 #include <iostream>
class definition
2 using namespace std;
3of GradeBook
4 // GradeBook class definition
5 class GradeBook {
6 public: Details later
7 // Member function Member function welcome
8 void welcome() {
9 cout << "Welcome to the Grade Book!" << endl;
10 }
11 }; End of class body. Note the
12 semicolon (;) at the end
13 … // Continue next page
• Example:
GradeBook book1, book2; // Two objects
// Call welcome of object book1
book1.welcome();
// Call welcome of object book2
book2.welcome();
13
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class GradeBook {
6 public:
7 void setCourseName(string name) {
8 courseName = name;
9 }
10
11 string getCourseName() {
12 return courseName;
13 }
14
15 void welcome() {
16 cout << "Welcome to the grade book for "
17 << getCourseName() << "!" << endl;
18 }
19 Data members are declared inside a
20 private: class, but outside all member functions
21 string courseName;
22 int grades[10]; // Assume 10 students
23 };
14
Instance Variables/Data Members
• Variables declared inside a class but outside any
member functions are instance variables
• They are carried within objects
• They are accessible (can be used) by all methods within
that class
int main() {
GradeBook book1, book2;
…
}
17
Why private Data Members?
• Declaring data members private is known as
information hiding
int main() {
Foo obj;
obj.x = 10; // Ok
obj.y = 20; // Compilation error
…
} 19
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
“set” function modifies
5 class GradeBook { private data
6 public:
7 void setCourseName(string name) {
8 courseName = name;
9 }
10 “get” function accesses
11 string getCourseName() { private data
12 return courseName;
13 }
14
15 void welcome() {
16 cout << "Welcome to the grade book for "
17 << getCourseName() << "!" << endl;
18 }
19
20 private:
21 string courseName;
22 int grades[10]; // Assume 10 students
23 };
20
24 Modify private data member
25 int main() { through public member functions
26 GradeBook myGradeBook;
27
28 myGradeBook.setCourseName("CSCI1357");
29 cout << "Course name is: "
30 << myGradeBook.getCourseName() << endl;
31
32 myGradeBook.setCourseName("CSCI2468");
33 cout << "Course name is now: "
34 << myGradeBook.getCourseName() << endl;
35
36 myGradeBook.welcome();
37
38 return 0; Access private data member
39 } through public member functions
Course name is: CSCI1357 courseName “CSCI2468”
“CSCI1357”
?
Course name is now: CSCI2468
Welcome to the grade book for CSCI2468! grades ? ? … ?
void setCourseName(…) {…}
string getCourseName() {…}
myGradeBook void welcome() {…}
21
Initializing Objects with
Constructors
• An object, upon creation, maintains its own copy of
attributes
• The initial values of the attributes can be garbage
values myGradeBook courseName ?
grades ? ? … ?
void setCourseName(…) {…}
string getCourseName() {…}
void welcome() {…}
22
Initializing Objects with
Constructors
• A constructor is like a member function, but:
• must be defined with the same name as the class
• cannot return values (not even void)
• can have parameters (specifying what to initialize)
class GradeBook {
public:
GradeBook(string name, int scores[]) {
Constructor name
setCourseName(name);
same as class name for (int i = 0; i < 10; i++)
if (scores[i] > 100)
grades[i] = 100;
No return type else
(not even void) grades[i] = scores[i];
}
… Perform initialization in
}; the constructor body 23
Calling a Constructor
int main() {
int scores1[10] = {70, 80, 83, 57, 96,
64, 72, 100, 66, 82};
int scores2[10] = {99, 80, 91, 71, 64,
64, 76, 77, 89, 51};
return 0;
}
Course 1 name is: CSCI1357
Course 2 name is: CSCI2468 24
Default Constructor
• If you do not provide any constructors to your class,
the compiler will automatically insert a default
constructor with no parameters for you
• Default constructor:
GradeBook() { // No parameter
// Default constructor does nothing
}
25
Rule of Thumb
26
Default Constructor: Pitfall
• Caution: If you have provided your own
constructor, the compiler will not insert a default
constructor anymore, so…
class Date {
public:
// No more default constructor
Date(int y, int m, int d) {
year = y; month = m; day = d;
}
private:
int year, month, day;
Tries to automatically call };
the default constructor, int main() {
which does not exist! Date xmas(2024, 12, 25); // Ok
Date myDate; // Compile ERROR
return 0;
} 27
Solution: Overloading Constructors
class Date {
public:
Date() { // Constructor #1
year = 1970; month = 1; day = 1;
}
foo(book);
return 0;
} 31
Object as Reference Parameter
courseName ? book (main),
grades ? ? … ? bk (foo) Passing object by reference
… // Methods
incurs no object assignment
foo(book);
return 0;
} 32
Reusing a Class
• One benefit of creating a class is that, when
packaged properly, our class can be reused by other
programmers
int main() {
…
} 33
Separating a Class from its Client
• We can split our program into three parts
Program Part File Remarks
1. Class GradeBook.cpp The implementation
implementation of all the member
file functions of class
GradeBook
2. Client program client.cpp The application
program
3. Header file GradeBook.h An interface between
Gradebook.cpp and
client.cpp
34
Rule of Thumb
35
Header File as an Interface
• The header file contains only the prototypes of the
member functions and the data members
• It specifies what (but not how) operations are provided
for a class
1 #include <string> GradeBook.h
2 using namespace std;
3
4 class GradeBook {
5 public:
6 GradeBook(string name, int scores[]);
7 void setCourseName(string name);
Prototypes only
8 string getCourseName();
9 void welcome();
10
11 private:
12 string courseName;
13 int grades[10]; // Assume 10 students
14 }; 36
1 #include <iostream> GradeBook.cpp
2 #include "GradeBook.h"
3
4
using namespace std; Class Implementation File
5 GradeBook::GradeBook(string name, int scores[]) {
6 setCourseName(name);
7 for (int i = 0; i < 10; i++) Include header file to access
8 if (scores[i] > 100) class name GradeBook
9 grades[i] = 100; • Quotes "…": programmer-
10 else defined header file
11 grades[i] = scores[i]; • Angle brackets <…>: C++
12 } built-in libraries
13
14 void GradeBook::setCourseName(string name) {
15 courseName = name;
16 } The operator ::
17 “ties” a function
18 string GradeBook::getCourseName() { to its class
19 return courseName;
20 }
21
22 void GradeBook::welcome() { No main
23 cout << "Welcome to the grade book for "
24 << getCourseName() << "!" << endl; function here
25 }
37
Client Program
1 #include <iostream> client.cpp
2 #include "GradeBook.h" Also needs to
3 using namespace std;
include header file
4
5 int main() {
6 int scores1[10] = {70, 80, 83, 57, 96,
7 64, 72, 100, 66, 82};
8 int scores2[10] = {99, 80, 91, 71, 64,
9 64, 76, 77, 89, 51};
10
11 GradeBook book1("CSCI1357", scores1);
12 GradeBook book2("CSCI2468", scores2);
13
14 cout << "Course 1 name is: "
15 << book1.getCourseName() << endl;
16 cout << "Course 2 name is: "
17 << book2.getCourseName() << endl;
18
19 return 0;
20 } 38
Class Implementation vs Client
• Class implementation is independent to its client
• Client cannot see how a class is implemented
#include <string>
using namespace std;
class GradeBook {
public:
GradeBook.h
GradeBook(string name, int scores[]);
void setCourseName(string name);
#include <iostream> string getCourseName();
#include "GradeBook.h"
using namespace std;
Class interface
void welcome();
private:
GradeBook::GradeBook(string name, int scores[]) { string courseName;
setCourseName(name); int grades[10]; // Assume 10 students #include <iostream>
for (int i = 0; i < 10; i++) }; #include "GradeBook.h"
if (scores[i] > 100) using namespace std;
grades[i] = 100;
else int main() {
grades[i] = scores[i]; int scores1[10] = {70, 80, 83, 57, 96,
} GradeBook.cpp client.cpp 64,
72, 100, 66, 82};
int scores2[10] = {99,
80, 91, 71, 64,
Class =implementation
void GradeBook::setCourseName(string name) {
courseName name; Client program 64,
76, 77, 89, 51};
… d … d … d … d … d … d
… m … m … m 12
… m … m … … m
… y … y … y … y … y … y
dates[0] dates[1] dates[2] dates[3] dates[4] dates[99]
(Methods inside objects are not shown for clarity) 45
(Optional)
Arrays of Objects
… d … d … d … d … d … d
… m … m … m … m … m … … m
… y … y … y … y … y … y
dates[0] dates[1] dates[2] dates[3] dates[4] dates[99]
Expression Meaning
dates An array of Date
Type: Date []
dates[3] The 4th element of the array
Type: Date
dates[3].setMonth(12) Call the setMonth() member
function of the 4th element of the array
46
(Optional)
Pointer to Objects
• Pointers can be set up to aim at objects
• (*datePtr) is the same as today
• Member access operator (.) has higher
int main() {
precedence than dereference operator (*)
Date today;
Date *datePtr;
today
datePtr
datePtr = &today; 25
? d
(*datePtr).setYear(2046); 12
? m
(*datePtr).setMonth(12);
2046
? y
(*datePtr).setDay(25);
if (today.getDay() == 25 && today.getMonth() == 12)
cout << "Merry Christmas!" << endl;
return 0;
} (Again, methods inside object are not shown for clarity)47
(Optional)
return 0;
} 48
Summary
• Understand the terms object, class, member function,
and data members
• Able to define a class with member functions and data
members
• Know how to initialize objects with constructors
• Understand the importance of information hiding
• Understand the benefits of separating class
implementation from client programs with an interface
• Manipulate objects with pointers and arrays (Optional)
Next: Strings
49