Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views49 pages

Lec12 Oop

Uploaded by

Mamat Rahmat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views49 pages

Lec12 Oop

Uploaded by

Mamat Rahmat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

CSCI1540

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

• Models communication among


objects by message sending

• A “bank account object” receives a


message (from an “ATM object”) to
decrease its balance by a certain amount

“Decrease
your balance
by $300”
4
Object-Oriented Programming
(OOP)
• Programming in object oriented languages is called
object-oriented programming (OOP)

• C++ is an object-oriented language


• Programmers can create user-defined types called
classes
• Classes contain data members (attributes) and member
functions (behaviors)

5
Classes and Objects
• Classes are blueprints to create objects

• We can create many objects from one class


• A car company can manufacture many car objects from
a car blueprint (design)
• You can drive a car, but not its blueprint

class objects

6
Class
• A class contains some data and a set of functions
that manipulate those data

• The function components are called member


functions (also called instance methods)

• The data components are called data members


(also called instance variables)

7
Case Study
• Dr. Law teaches many courses

• He wants to implement a grade book program to


maintain students’ exam scores of each course

• We shall define a class (data type) called


GradeBook for the purpose

• Let’s start with a simple class that contains simply a


member function

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

Naming convention: the name of a programmer-


defined class usually starts in capital letter 9
Defining a Class with Member
Function
14 … // Continue from previous page
15
16 int main() {
17 // Create a GradeBook object named myGradeBook
18 GradeBook myGradeBook;
Declare a
19
20 // Call object's member function variable of type
21 myGradeBook.welcome(); GradeBook
22
23 return 0;
24 } Use a dot (.) to call an
object’s member function
Welcome to the Grade Book!

• myGradeBook is called an object/instance of class GradeBook


• The main function is called a client of class GradeBook 10
Dot Operator (.)
• The dot (.) operator is used to access an object’s
data members and member functions

• Example:
GradeBook book1, book2; // Two objects
// Call welcome of object book1
book1.welcome();
// Call welcome of object book2
book2.welcome();

(Send a welcome message to book1) (Send a welcome message to book2)


void welcome() { void welcome() {
book1 … … book2
} }
11
public and private Access
Specifiers
The keyword public specifies that the member functions after it are
“available to the public”, i.e., can be called from outside of a class
class GradeBook {
public:
void welcome() {

} int main() {
private: GradeBook book;
void foo() { book.welcome(); // Ok
… book.foo(); // Compile-error
} …
}; }

It is possible to deny outsiders to call a


member function using the keyword private 12
Defining Data Members in a Class
• An object of class GradeBook is used to store the
exam scores of the students in a course

• A straightforward choice of attributes of class


GradeBook is:
• Name of the course (string)
• An array of the students’ scores (array of integers)

• Let’s expand the GradeBook class with these two


attributes

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;

}

book1 courseName ? courseName ? book2


grades ? ? … ? grades ? ? … ?
void welcome() { void welcome() {
… … … …
} }
15
Local variable
Local Variables vs Instance Instance variable

Variables class Foo {


public:
void method( int param ) {
• Variables declared int localVar = 1;
inside a …
instVar = 2; // Ok
function/method } f instVar …
(including parameters) private:
… // Method
are local variables int instVar;
}; param 6
• Local variables are int main() { localVar 1
accessible within that localVar = 3; // Error
method only instVar = 5; // Error
Foo f;
Do NOT write:
f.instVar = 4; // Error: private
int instVar = 3;
f.method(6); // Ok
for initialization
return 0;
} 16
Rule of Thumb
• When defining a class:

All data members of a class should be declared


private

Member functions should generally be public


(There can be private member functions
sometimes nonetheless)

17
Why private Data Members?
• Declaring data members private is known as
information hiding

• When a program creates a GradeBook object, the


data members courseName and grades are
encapsulated (hidden) in the object
• They can be accessed only by member functions of
the object’s class
book1 courseName ?
grades ? ? … ?
void welcome() {
… …
}
18
Why private Data Members?
Class Foo
• Information hiding Main function (client)

facilitates debugging, class Foo {


public:
because problems int x;
with data …
manipulations are private:
localized to within the int y;

class only };

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() {…}

• How can we initialize the attributes of an object


when the object is created?
• Use a constructor

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};

GradeBook book1("CSCI1357", scores1);


GradeBook book2("CSCI2468", scores2);
Calling the
cout << "Course 1 name is: " constructor
<< book1.getCourseName() << endl; implicitly
cout << "Course 2 name is: "
<< book2.getCourseName() << endl;

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
}

• Do NOT rely on the default constructor!

25
Rule of Thumb

Always provide a public constructor to


your class to initialize all data members
when a new object of your class is created

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;
}

Date(int y, int m, int d) { // Constructor #2


year = y; month = m; day = d;
}
private: Provide multiple
int year, month, day; (overloaded) constructors,
}; one of which a default one
int main() {
Date xmas(2024, 12, 25); // 25 Dec 2024
Date myDate; // 1 Jan 1970
return 0;
} 28
Object Assignment
• The assignment operator = can be applied to
objects: book1 = book2;
• Individual data member of the RHS object is copied to
the corresponding data member of the LHS object

book1 courseName ? courseName ? book2


grades ? ? … ? grades ? ? … ?
… // Methods … // Methods

• This applies even to array members in an object, i.e., it


also makes a copy of the array member inside the object
Object assignment can be time consuming
if you have a HUGE object 29
Object Assignment
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};

GradeBook book1("CSCI1357", scores1);


GradeBook book2("CSCI2468", scores2);

book1 = book2; // Object assignment

cout << "Course 1 name is: "


<< book1.getCourseName() << endl;
cout << "Course 2 name is: "
<< book2.getCourseName() << endl;

return 0; Course 1 name is: CSCI2468


} Course 2 name is: CSCI2468 30
Implicit Object Assignment
Object arguments are pass-by-value by
default (unless reference parameters
are used). This is also object assignment
void foo(GradeBook bk) {

}
(Implicit object copying)
int main() {
int scores[10] = {70, 80, 83, 57, 96, 64, 72, 100, 66, 82};

GradeBook book("CSCI1357", scores);

foo(book);

return 0;
} 31
Object as Reference Parameter
courseName ? book (main),
grades ? ? … ? bk (foo) Passing object by reference
… // Methods
incurs no object assignment

void foo(GradeBook &bk) {



}
(Create alias only. No object copying)
int main() {
int scores[10] = {70, 80, 83, 57, 96, 64, 72, 100, 66, 82};

GradeBook book("CSCI1357", scores);

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

• Up to now, we write our class GradeBook and


main function in the same source file. This
prevents the class from being reused
class GradeBook { xxx.cpp

};

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

Always use the class name as the file


names of the class implementation
and header files

• E.g.: class name is GradeBook


• Implementation file: GradeBook.cpp
• Header file: GradeBook.h

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};

} GradeBook book1("CSCI1357", scores1);


GradeBook book2("CSCI2468", scores2);
string GradeBook::getCourseName() {
return courseName; cout << "Course 1 name is: "
} << book1.getCourseName() << endl;
cout << "Course 2 name is: "
void GradeBook::welcome() { << book2.getCourseName() << endl;
cout << "Welcome to the grade book for "
<< getCourseName() << "!" << endl; return 0;
} } 39
• Let’s enrich our class GradeBook
To Wrap Up… to include more functionalities
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); // Set the course name
8 string getCourseName(); // Retrieve the course name
9 void welcome(); // Print a welcome message
10 void processGrades(); // Perform various operations
11 int getMax(); // Find the max score
12 int getMin(); // Find the min score
13 double getAverage(); // Compute the average score
14 void outputGrades(); // Print all the scores
15
16 private:
17 string courseName;
18 int grades[10]; // Assume 10 students
19 }; 40
1 #include <iostream> GradeBook.cpp
2 #include <iomanip>
3 #include "GradeBook.h"
4 using namespace std;
5
6 GradeBook::GradeBook(string name, int scores[]) {
7 setCourseName(name);
8 for (int i = 0; i < 10; i++)
9 if (scores[i] > 100)
10 grades[i] = 100;
11 else
12 grades[i] = scores[i];
13 }
14
15 void GradeBook::setCourseName(string name) {
16 courseName = name;
17 }
18
19 string GradeBook::getCourseName() {
20 return courseName;
21 }
41
22 GradeBook.cpp (continue)
23 void GradeBook::welcome() {
24 cout << "Welcome to the grade book for "
25 << getCourseName() << "!" << endl;
26 }
27
28 void GradeBook::processGrades() {
29 outputGrades();
30 cout << "Class average is " << getAverage() << endl;
31 cout << "Lowest grade is " << getMin() << endl;
32 cout << "Highest grade is " << getMax() << endl;
33 }
34
35 int GradeBook::getMax() {
36 int largest = 0;
37 for (int i = 0; i < 10; i++)
38 if (grades[i] > largest)
39 largest = grades[i];
40 return largest;
41 }
42
42
43 int GradeBook::getMin() { GradeBook.cpp (continue)
44 int smallest = 100;
45 for (int i = 0; i < 10; i++)
46 if (grades[i] < smallest)
47 smallest = grades[i];
48 return smallest;
49 }
50
51 double GradeBook::getAverage() {
52 int sum = 0;
53 for (int i = 0; i < 10; i++)
54 sum += grades[i];
55 return (double)sum / 10;
56 }
57
58 void GradeBook::outputGrades() {
59 cout << "The grades are:" << endl;
60 for (int i = 0; i < 10; i++)
61 cout << "Student " << setw(3) << i + 1 << ":"
62 << setw(10) << grades[i] << endl;
63 }
43
1 #include "GradeBook.h" client.cpp
2
3 int main() {
4 int scores[10] = {87, 68, 94, 100, 83,
5 78, 85, 91, 76, 87};
6
7 GradeBook book("CSCI1357", scores);
8
9 book.welcome();
10 book.processGrades();
11 Welcome to the grade book for CSCI1357!
12 return 0; The grades are:
13 } Student 1: 87
Student 2: 68
Student 3: 94
Student 4: 100
GradeBook.h Student 5: 83
Student 6: 78
Student 7: 85
Student 8: 91
Student 9: 76
GradeBook.cpp client.cpp Student 10: 87
Class average is 84.9
Lowest grade is 68
Highest grade is 100 44
class Date { (Optional)

Arrays of Objects private:
int d, m, y;
};
Date dates[100]; // An array of 100 Date objects
int newYrCnt = 0;

dates[3].setMonth(12); // Set member m of 4th element to 12



for (int i = 0; i < 100; i++)
if (dates[i].getDay() == 1 && dates[i].getMonth() == 1)
newYrCnt++;
cout << "Num of New Year = " << newYrCnt << endl;

… 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)

Arrow Member Selection


Operator ->
• optr->mem is a shorthand for (*optr).mem
• optr must be a pointer aiming at a proper object
• mem should be defined in the class definition
int main() {
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;
} 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

You might also like