0% found this document useful (0 votes)
16 views15 pages

C++ Classes and OOP Basics

Uploaded by

nick koech
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)
16 views15 pages

C++ Classes and OOP Basics

Uploaded by

nick koech
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

1

CS 103 Unit 10 Slides

C++ Classes

Mark Redekopp
2

Object-Oriented Approach
• Model the application/software as a set of objects that interact
with each other
• Objects fuse data (i.e. variables) and functions (a.k.a methods)
that operate on that data into one item (i.e. object)
• Objects replace global-level functions as the primary method of
encapsulation and abstraction
– Encapsulation: Hiding implementation and controlling access
• Group data and code that operates on that data together into one unit
• Only expose a well-defined interface to control misuse of the code by other
programmers
– Abstraction
• Hiding of data and implementation details
• How we decompose the problem and think about our design at a higher level rather
than considering everything at the lower level
3

Object-Oriented Programming
• Objects contain:
– Data members
• Data needed to model the object and track its state/operation
(just like structs)
– Methods/Functions
• Code that operates on the object, modifies it, etc.
• Example: Deck of cards
– Data members:
• Array of 52 entries (one for each card) indicating their ordering
• Top index
– Methods/Functions
• shuffle(), cut(), get_top_card()
4

C++ Classes
#include <iostream>
using namespaces std;
• Classes are the programming construct used class Deck {
public:
to define objects, their data members, and Deck(); // Constructor
int get_top_card();
methods/functions private:
• Similar idea to structs int cards[52];
int top_index;
• Steps: };

– Define the class’ data members and // member function implementation

[Link]
Deck::Deck()
function/method prototypes {
for(int i=0; i < 52; i++)
– Write the methods cards[i] = i;
– Instantiate/Declare object variables and use }
int Deck::get_top_card()
them by calling their methods {
return cards[top_index++];
• Terminology: }
// Main application
– Class = Definition/Blueprint of an object int main(int argc, char *argv[]) {
Deck d;
– Object = Instance of the class, actual int hand[5];
allocation of memory, variable, etc. [Link]();
[Link]();
for(int i=0; i < 5; i++){
hand[i] = d.get_top_card();
}
...
5

Common C++ Class Structure


class Deck {
public:
Deck(); // Constructor
• Common to separate class into separate ~Deck(); // Destructor
void shuffle();
source code files so it can easily be reused

deck.h
void cut();
in different applications int get_top_card();
private:
• Steps: int cards[52];
int top_index;
– Define the class’: };

1.) data members and


#include<iostream>

[Link]
2.) function/method prototypes #include "deck.h"
(usually in a separate header file)
– Must define the class using the syntax: // Code for each prototyped method

• class name { ... }; #include<iostream>


#include "deck.h"
– Write the methods (usually in a separate
.cpp file) int main(int argc, char *argv[]) {

[Link]
Deck d;
– Instantiate/Declare object variables and use int hand[5];
them by calling their methods [Link]();
[Link]();
for(int i=0; i < 5; i++){
hand[i] = d.get_top_card();
}
}
6

Access Specifiers
class Deck {
• Each function or data member can be classified public:
Deck(); // Constructor
as public, private, or protected ~Deck(); // Destructor (see next slide)
– These classifications support encapsulation by void shuffle();
void cut();

deck.h
allowing data/method members to be int get_top_card();
inaccessible to code that is not a part of the class private:
(i.e. only accessible from within a public class int cards[52];
int top_index;
method) to avoid mistakes by other programmers };
– Ensure that no other programmer writes code
that uses or modifies your object in an #include<iostream>

[Link]
#include “deck.h”
unintended way
– Private: Can call or access only by // Code for each prototyped method
methods/functions that are part of that class
#include<iostream>
– Public: Can call or access by any other code #include “deck.h”
– Protected: More on this in CS 104
int main(int argc, char *argv[]) {
• Everything private by default so you must Deck d;

[Link]
int hand[5];
use public: to make things visible
[Link]();
• Make the interface public and the [Link]();
[Link][0] = ACE; //won’t compile
guts/inner-workings private d.top_index = 5; //won’t compile
}
7

Constructors / Destructors
class Deck {

deck.h
public:
Deck(); // Constructor
• Constructor is a function of the same name as ~Deck(); // Destructor
the class itself ...
};
– It is called automatically when the object is
created (either when declared or when allocated #include<iostream>
#include “deck.h”
via ‘new’)
– Use to initialize your object (data members) to Deck::Deck() {
desired initial state top_index = 0;
for(int i=0; i < 52; i++){

[Link]
– Returns nothing cards[i] = i;
• Destructor is a function of the same name }
}
as class itself with a ‘~’ in front
Deck::~Deck() {
– Called automatically when object goes out of }
scope (i.e. when it is deallocated by ‘delete’ or
#include<iostream>
when scope completes) #include "deck.h"

[Link]
– Use to free/delete any memory allocated by the
int main() {
object or close any open file streams, etc. Deck d; // Deck() is called
– Returns nothing ...

– [Note: Currently we do not have occasion to use return 0;


// ~Deck() is called since
destructors; we will see reasons later on in the // function is done
course] }
8

Writing Member Functions


class Deck {
• What's wrong with the code on the left vs. public:

deck.h
Deck(); // Constructor
code on the right ~Deck(); // Destructor
void f1() Deck::Deck() void shuffle();
{ { ...
top_index = 0; top_index = 0; };
} }
#include<iostream>
#include "deck.h"
• Compiler needs to know that a function is a Deck::Deck() {
member of a class top_index = 0;
for(int i=0; i < 52; i++){
• Include the name of the class followed by }
cards[i] = i;

‘::’ just before name of function }


Deck::~Deck()
• This allows the compiler to check access to {

[Link]
}
private/public variables
– Without the scope operator [i.e. void Deck::shuffle()
{
int get_top_card() rather than cut(); //calls cut() for this object
int Deck::get_top_card() ] the compiler ...
would think that the function is some outside }
int Deck::get_top_card()
function (not a member of Deck) and thus generate {
an error when it tried to access the data members top_index++;
(i.e. cards array and top_index). return cards[top_index-1];
}
9

Multiple Constructors
class Student {
• Can have multiple public:
Student(); // Constructor 1
constructors with different Student(string name, int id, double gpa);
// Constructor 2
argument lists

student.h
~Student(); // Destructor
string get_name();
int get_id();
double get_gpa();
void set_name(string name); Note: Often name
void set_id(int id);
void set_gpa(double gpa);
data members with
#include<iostream> private: special decorator
#include "student.h" string name_; (id_ or m_id) to make
int main() int id_; it obvious to other
{ double gpa_; programmers that
Student s1; // calls Constructor 1 }; this variable is a data
string myname; Student::Student() member
cin >> myname; {
s1.set_name(myname); name_ = “”, id_ = 0; gpa_ = 2.0;
s1.set_id(214952); }

[Link]
s1.set_gpa(3.67);
Student::Student(string name, int id, double gpa)
Student s2(myname, 32421, 4.0); {
// calls Constructor 2 name_ = name; id = id_; gpa = gpa_;
} }
10

Accessor / Mutator Methods


class Student {
• Define public "get" (accessor) and public:
Student(); // Constructor 1
"set" (mutator) functions to let other Student(string name, int id, double gpa);
code access desired private data // Constructor 2

student.h
~Student(); // Destructor
members string get_name() const;
int get_id() const;
• Use 'const' after argument list for double get_gpa() const;
accessor methods void set_name(string s);
void set_id(int i);
– Ensures data members are not altered void set_gpa(double g);
private:
by this function (more in CS 104) string _name;
int _id;
#include<iostream>
double _gpa;
#include “deck.h”
};
int main()
{
string Student::get_name() const
Student s1; string myname;
{ return _name; }

[Link]
cin >> myname;
int Student::get_id() const
s1.set_name(myname);
{ return _id; }
string another_name; void Student::set_name(string s)
another_name = s1.get_name(); { _name = s; }
... void Student::set_gpa(double g)
{ _gpa = g; }
}
11

Calling Member Functions (1)


cards[52] 0 1 2 3 4 5 6 7
d1
• When outside the class scope top_index
0
(i.e. in main or some outside cards[52]
d2 0 1 2 3 4 5 6 7
function)
top_index
0
– Must precede the member
function call with the name of the #include<iostream>
#include "deck.h"
specific object that it should
operate on (i.e. [Link]()) int main() {
Deck d1, d2;
– [Link]() indicates the int hand[5];

code of shuffle() should be [Link]();


// not [Link]() or
operating implicitly on d1's data // shuffle(d1), etc.
member vs. d2 or any other Deck for(int i=0; i < 5; i++){
hand[i] = d1.get_top_card();
object }
}

cards[52] 41 27 8 39 25 4 11 17
d1 top_index
1
12

Calling Member Functions


#include<iostream>
• When inside the class scope (i.e. in #include “deck.h”
main or some outside function) int main(int argc, char *argv[]) {

[Link]
• Within a member function we can just Deck d1, d2;
int hand[5];
call other member functions directly. [Link]();
...
}

d1’s data will be modified d1 is implicitly


#include<iostream>
(shuffled and cut) passed to shuffle() #include “deck.h”
void Deck::shuffle()
cards[52] 41 27 8 39 25 4 11 17 {
d1 top_index
cut(); // calls cut()
0 // for this object
for(i=0; i < 52; i++){
int r = rand() % (52-i);

[Link]
int temp = cards[r];
cards[52] 0 1 2 3 4 5 6 7 cards[r] = cards[i];
d2 cards[i] = temp;
top_index }
0
}
void Deck::cut()
Since shuffle was implicitly {
// swap 1st half of deck w/ 2nd
working on d1’s data, d1 is
}
again implicitly passed to cut()
13

Exercises
• In-class Exercises
14

Class Pointers
cards[52] 0 1 2 3 4 5 6 7
d1
• Can declare pointers to these top_index
0
new class types cards[52]
d2 0 1 2 3 4 5 6 7
• Use ‘->’ operator to access top_index
0
member functions or data
#include<iostream>
#include "deck.h"

int main(int argc, char *argv[]) {


Deck *d1;
int hand[5];
d1 = new Deck;
d1->shuffle();
for(int i=0; i < 5; i++){
hand[i] = d1->get_top_card();
}
}

cards[52] 41 27 8 39 25 4 11 17
d1 top_index
5
15

Public / Private and Structs vs. Classes


• In C++ the only difference between structs and classes is
structs default to public access, classes default to private
access
• Thus, other code (non-member functions of the class) cannot
access private class members directly

student.h [Link]
class Student { // what's the difference #include<iostream>
struct Student { // between these two #include "student.h"
int main()
Student(); // Constructor 1 {
Student(string name, int id, double gpa); Student s1; string myname;
// Constructor 2 cin >> myname;
~Student(); // Destructor s1._name = myname;
... // compile error if 'class' but not
string name_; // if 'struct'
int id_; ...
double gpa_; }
};

You might also like