15
1 CS 103 Unit 10 Slides C++ Classes Mark Redekopp

CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

1

CS103Unit10Slides

C++Classes

MarkRedekopp

Page 2: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

2

Object-OrientedProgramming• Modeltheapplication/softwareasasetofobjectsthatinteract

witheachother• Objectsfusedata (i.e.variables)andfunctions (a.k.a methods)

thatoperateonthatdataintooneitem(i.e.object)– Likestructs butnowwithassociatedfunctions/methods

• Objectsbecometheprimarymethodofencapsulationandabstraction– Encapsulation

• Hidingofdataandimplementationdetails(i.e.makesoftwaremodular)• Onlyexposeawell-definedinterfacetoanyonewantingtouseourobject

– Abstraction• Howwedecomposetheproblemandthinkaboutourdesignratherthantheactual

code

Page 3: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

3

Objects

• Objectscontain:– Datamembers

• Dataneededtomodeltheobjectandtrackitsstate/operation(justlikestructs)

– Methods/Functions• Codethatoperatesontheobject,modifiesit,etc.

• Example:Deckofcards– Datamembers:

• Arrayof52entries(oneforeachcard)indicatingtheirordering• Topindex

– Methods/Functions• Shuffle(),Cut(),Get_top_card()

Page 4: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

4

C++Classes• Classesaretheprogrammingconstructused

todefine objects,theirdatamembers,andmethods/functions

• Similarideatostructs• Steps:

– Definetheclass’datamembersandfunction/methodprototypes

– Writethemethods– Instantiate/Declareobjectvariablesanduse

thembycallingtheirmethods

• Terminology:– Class =Definition/Blueprintofanobject– Object =Instanceoftheclass,actual

allocationofmemory,variable,etc.

#include <iostream>using namespaces std;class Deck {public:Deck(); // Constructorint get_top_card();

private:int cards[52];int top_index;

};

// member function implementationDeck::Deck(){for(int i=0; i < 52; i++)cards[i] = i;

}int Deck::get_top_card() {

return cards[top_index++];}// Main applicationint main(int argc, char *argv[]) {Deck d;int hand[5];d.shuffle();d.cut();for(int i=0; i < 5; i++){hand[i] = d.get_top_card();

}...

poker.cpp

Page 5: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

5

C++Classes• Classesaretheprogrammingconstructused

todefine objects,theirdatamembers,andmethods/functions

• Similarideatostructs• Steps:

– Definetheclass’datamembersandfunction/methodprototypes(usuallyinaseparateheaderfile)

– Writethemethods(usuallyinaseparate.cpp file)

– Instantiate/Declareobjectvariablesandusethembycallingtheirmethods

• Terminology:– Class =Definition/Blueprintofanobject– Object =Instanceoftheclass,actual

allocationofmemory,variable,etc.

class Deck {public:Deck(); // Constructor~Deck(); // Destructorvoid shuffle();void cut();int get_top_card();

private:int cards[52];int top_index;

};

#include<iostream>#include “deck.h”

// Code for each prototyped method

#include<iostream>#include “deck.h”

int main(int argc, char *argv[]) {Deck d;int hand[5];

d.shuffle();d.cut();for(int i=0; i < 5; i++){hand[i] = d.get_top_card();

}}

deck.hdeck.cpp

poker.cpp

Page 6: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

6

ClassDefinition• classname {…};• Eachfunctionordatamembercanbeclassified

aspublic,private,orprotected– Theseclassificationssupportencapsulationby

allowingdata/methodmemberstobeinaccessibletocodethatisnotapartoftheclass(i.e.onlyaccessiblefromwithinapublicclassmethod)

– Ensurethatnootherprogrammerwritescodethatusesormodifiesyourobjectinanunintendedway

– Private:Cancalloraccessonlybymethods/functionsthatarepartofthatclass

– Public:Cancalloraccessbyanyothercode– Protected:Moreonthislater

• Everythingprivatebydefaultsoyoumustuse“public:”tomakethingsvisible

• Maketheinterfacepublicandtheguts/inner-workingsprivate

class Deck {public:Deck(); // Constructor~Deck(); // Destructorvoid shuffle();void cut();int get_top_card();

private:int cards[52];int top_index;

};

#include<iostream>#include “deck.h”

// Code for each prototyped method

#include<iostream>#include “deck.h”

int main(int argc, char *argv[]) {Deck d;int hand[5];

d.shuffle();d.cut();

d.cards[0] = ACE; //won’t compiled.top_index = 5; //won’t compile

}

deck.hdeck.cpp

poker.cpp

Page 7: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

7

Constructors/Destructors• Constructor isafunctionofthesamenameas

theclassitself– Itiscalledautomaticallywhentheobjectis

created(eitherwhendeclaredorwhenallocatedvia‘new’)

– Usetoinitializeyourobject(datamembers)todesiredinitialstate

– Returnsnothing

• Destructor isafunctionofthesamenameasclassitselfwitha‘~’infront– Calledautomaticallywhenobjectgoesoutof

scope(i.e.whenitisdeallocated by‘delete’orwhenscopecompletes)

– Usetofree/deleteanymemoryallocatedbytheobject

– Returnsnothing– [Note:Currentlywedonothaveoccasiontouse

destructors;wewillseereasonslateroninthecourse]

class Deck {public:Deck(); // Constructor~Deck(); // Destructor...

};

#include<iostream>#include “deck.h”

Deck::Deck() {top_index = 0;for(int i=0; i < 52; i++){cards[i] = i;

}

}

Deck::~Deck() {}

#include<iostream>#include “deck.h”

int main(int argc, char *argv[]) {Deck d; // Deck() is called...

return 1;// ~Deck() is called since// function is done

}

deck.hdeck.cpp

poker.cpp

Page 8: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

8

WritingMemberFunctions• Whenwritingmemberfunctions,the

compilersomehowneedstoknowthatthefunctionisamemberofaparticularclassandthatthefunctionhasinherentaccesstodatamembers(w/odeclaringthem).Thuswemust‘scope’ourfunctions

• Includethenameoftheclassfollowedby‘::’ justbeforenameoffunction

• Thisallowsthecompilertocheckaccesstoprivate/publicvariables– Withoutthescopeoperator[i.e.voidshuffle()

ratherthanvoidDeck::shuffle()]thecompilerwouldthinkthatthefunctionissomeoutsidefunction(notamemberofDeck)andthusgenerateanerrorwhenittriedtoaccessthedatamembers(i.e.cardsarrayandtop_index).

class Deck {public:Deck(); // Constructor~Deck(); // Destructor...

};

#include<iostream>#include “deck.h”

Deck::Deck() {top_index = 0;for(int i=0; i < 52; i++){cards[i] = i;

}}

Deck::~Deck() {}

void Deck::shuffle(){cut(); //calls cut() for this object...

}

int Deck::get_top_card(){top_index++;return cards[top_index-1];

}

deck.hdeck.cpp

Page 9: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

9

CallingMemberFunctions• Memberfunctionsarecalledby

precedingtheirnamewiththespecificobjectthatitshouldoperateon

• d1.shuffle()indicatesthecodeofshuffle()shouldbeoperatingimplicitlyond1’sdatamembervs.d2oranyotherDeckobject

#include<iostream>#include “deck.h”

int main(int argc, char *argv[]) {Deck d1, d2;int hand[5];

d1.shuffle();// not Deck.shuffle() or// shuffle(d1), etc.

for(int i=0; i < 5; i++){hand[i] = d1.get_top_card();

}}

d1

d2 0 1 2 3 4 5 6 7cards[52]

0top_index

41 27 8 39 25 4 11 17cards[52]

1top_indexd1

0 1 2 3 4 5 6 7cards[52]

0top_index

Page 10: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

10

CallingMemberFunctions• Withinamemberfunctionwe

canjustcallothermemberfunctionsdirectly.

#include<iostream>#include “deck.h”

int main(int argc, char *argv[]) {Deck d1, d2;int hand[5];

d1.shuffle();...

}

#include<iostream>#include “deck.h”

void Deck::shuffle(){cut(); // calls cut()

// for this objectfor(i=0; i < 52; i++){int r = rand() % (52-i);int temp = cards[r];cards[r] = cards[i];cards[i] = temp;

} }void Deck::cut(){// swap 1st half of deck w/ 2nd

}

deck.cpppoker.cpp

41 27 8 39 25 4 11 17cards[52]

0top_indexd1

d2 0 1 2 3 4 5 6 7cards[52]

0top_index

d1 is implicitly passed to shuffle()

Since shuffle was implicitly working on d1’s data, d1 is

again implicitly passed to cut()

d1’s data will be modified (shuffled and cut)

Page 11: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

11

Exercises

• In-classExercises

Page 12: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

12

ClassPointers• Candeclarepointerstothese

newclasstypes• Use‘->’operatortoaccess

memberfunctionsordata#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();

}}

d1

d2 0 1 2 3 4 5 6 7cards[52]

0top_index

41 27 8 39 25 4 11 17cards[52]

5top_indexd1

0 1 2 3 4 5 6 7cards[52]

0top_index

Page 13: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

13

MultipleConstructors

• Canhavemultipleconstructorswithdifferentargumentlists

class Student {public:Student(); // Constructor 1Student(string name, int id, double gpa);

// Constructor 2~Student(); // Destructorstring get_name();int get_id();double get_gpa();

void set_name(string name);void set_id(int id);void set_gpa(double gpa);

private:string _name;int _id;double _gpa;

};

Student::Student(){_name = “”, _id = 0; _gpa = 2.0;

}

Student::Student(string name, int id, double gpa){_name = name; _id = id; _gpa = gpa;

}

deck.hdeck.cpp

#include<iostream>#include “deck.h”

int main(){Student s1; // calls Constructor 1string myname;cin >> myname;s1.set_name(myname);s1.set_id(214952);s1.set_gpa(3.67);

Student s2(myname, 32421, 4.0);// calls Constructor 2

}

Page 14: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

14

Public/PrivateandStructs vs.Classes• InC++theonlydifferencebetweenstructs andclassesis

structs defaulttopublicaccess,classesdefaulttoprivateaccess

• Thus,othercode(non-memberfunctionsoftheclass)cannotaccessprivateclassmembersdirectly

class Student {public:Student(); // Constructor 1Student(string name, int id, double gpa);

// Constructor 2~Student(); // Destructor...

private:string _name;int _id;double _gpa;

};

student.h#include<iostream>#include “student.h”

int main(){Student s1; string myname;cin >> myname;s1._name = myname; //compile error

...

}

grades.cpp

Page 15: CS 103 Unit 10 Slides - USC Bitsbits.usc.edu/files/cs103/slides/Unit10_Classes.pdf• Constructoris a function of the same name as the class itself – It is called automatically when

15

Accessor /Mutator Methods• Definepublic“get”(accessor)

and“set”(mutator)functionstoletothercodeaccessdesiredprivatedatamembers

• Use'const'afterargumentlistforaccessor methods

class Student {public:Student(); // Constructor 1Student(string name, int id, double gpa);

// Constructor 2~Student(); // Destructorstring get_name() const;int get_id() const;double get_gpa() const;

void set_name(string s);void set_id(int i);void set_gpa(double g);

private:string _name;int _id;double _gpa;

};

string Student::get_name(){ return _name; }int Student::get_id(){ return _id; }void Student::set_name(string s){ _name = s; }

void Student::set_gpa(double g){ _gpa = g; }

student.hstudent.cpp

#include<iostream>#include “deck.h”

int main(){Student s1; string myname;cin >> myname;s1.set_name(myname);

string another_name;another_name = s1.get_name();

...

}