cs 103 unit 9 – objects, structs, and...

34
1 CS 103 Unit 9 – Objects, Structs, and Strings Mark Redekopp

Upload: others

Post on 27-Jun-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

1

CS103Unit9–Objects,Structs,andStrings

MarkRedekopp

Page 2: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

2

OBJECTS

Page 3: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

3

TypesandInstances

• A'type'indicateshowmuchmemorywillberequired,whatthebitsmean(i.e.datavs.address),andwhatoperationscanbeperformed– int =32-bitsrepresentingonlyintegervaluesandsupporting+,-,*,/,=,==,<,>,etc.

– char* =32-bitrepresentinganaddressandsupporting*(dereference),&,+,- (butnotmultiplyanddivide)

– Typesarelikeblueprints forwhat&howtomakeaparticular'thing'

• Avariable orobject isanactualinstantiation(allocationofmemory)foroneofthesetypes– int x,doublez,char*str;

Page 4: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

4

AbstractDataTypes

• Oftentimeswewanttorepresentabstractthings(beyondaninteger,character,ordouble)– Examples:

• Apixel,acircle,astudent

• Oftentheseabstracttypescanberepresentedasacollectionofintegers,characterarrays/strings,etc.

• Apixel(withR,G,Bvalue)• Acircle(center_x,center_y,radius)• Astudent(name,ID,major)

• Objects(realizedas'structs'inCandlater'classes'inC++)allowustoaggregatedifferenttypevariablestogethertorepresentalarger'thing'aswellassupportingoperationsonthat'thing'– Canreferencethecollectionwithasinglename(pixelA,student1)– Canaccessindividualcomponents(pixelA.red,student1.id)

Page 5: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

5

Objects• Anobjectisagroupofdata+functions• Objectscontain:– Datamembers

• Dataneededtomodeltheobjectandtrackitsstate/operation(justlikestructs)

– Methods/Functions• Codethatoperatesontheobject,modifiesit,etc.

• Example:Deckofcards– Datamembers:

• Arrayof52entries(oneforeachcard)indicatingtheirordering• Topindex

– Methods/Functions• Deck.Shuffle(),Deck.Cut(),Deck.Deal()

Page 6: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

6

Structs vs.Classes

• Structs (originatedintheClanguage)arethepredecessorsofclasses (C++language)– Thoughstructs arestillvalidinC++

• Classes formthebasisof‘object-oriented’programmingintheC++language

• Botharesimplyawayofgroupingrelateddatatogetherandrelatedoperations (functionsormethods)tomodelsome'object'

• Themajorityofthefollowingdiscussionappliesbothtostructs andclasses equallysopayattentionnowtomakenextlectureeasier.

Page 7: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

7

Object-OrientedProgramming

• Modeltheapplication/softwareasasetofobjectsthatinteractwitheachother

• Objectsfusedata(i.e.variables)andfunctions(a.k.a methods)thatoperateonthatdataintooneitem(i.e.object)– Likestructs butnowwithassociatedfunctions/methods

• Objectsbecometheprimarymethodofencapsulationandabstraction– Encapsulation

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

– Abstraction• Howwedecomposetheproblemandthinkaboutourdesignratherthantheactual

code

Page 8: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

8

C++STRINGS

Page 9: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

9

CStrings

• InC,stringsare:– Characterarrays(charmystring[80])– TerminatedwithaNULLcharacter– Passedbyreference/pointer(char*)tofunctions– Requirecarewhenmakingcopies• Shallow(onlycopyingthepointer)vs.Deep(copyingtheentirearrayofcharacters)

– ProcessedusingCStringlibrary(<cstring>)

Page 10: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

10

StringFunction/Library(cstring)

• int strlen(char*dest)• int strcmp(char*str1,char*str2);

– Return0ifequal,>0iffirstnon-equalcharinstr1isalphanumericallylarger,<0otherwise

• char*strcpy(char*dest,char*src);– strncpy(char*dest,char*src,int n);– Maximumofncharacterscopied

• char*strcat(char*dest,char*src);– strncat(char*dest,char*src,int n);– MaximumofncharactersconcatenatedplusaNULL

• char*strchr(char*str,charc);– Findsfirstoccurrenceofcharacter‘c’instr returningapointertothat

characterorNULLifthecharacterisnotfound

#include <cstring>using namespace std;

int main() {char temp_buf[5];char str[] = "Too much";

strcpy(temp_buf, str); // badstrncpy(temp_buf, str, 4);temp_buf[4] = '\0';

return 0; }

InC,wehavetopasstheC-Stringasanargumentforthefunction

tooperateonit

Page 11: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

11

CopyingStrings/CharacterArraysinC

• HowtocopyaC-string?• Canwejustusethe

assignmentoperator,‘=‘withcharacterarrays?

• No,mustallocatenewstorage

temp_buf:0x1c0:

names[0] 0x1c0

names[1] 0x1c0

Timothy Christopher

#include <iostream>#include <cstring>using namespace std;

// store 10 user names of up to 80 chars// names type is still char **char *names[10];

int main(){

char temp_buf[100];

cin >> temp_buf; // user enters “Timothy”names[0] = temp_buf;

cin >> temp_buf; // user enters “Christopher”names[1] = temp_buf;

return 0;}

0x1c0:

Page 12: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

12

CopyingStrings/CharacterArraysinC

• No,mustallocatenewstorage

names[0] 0x2e0

names[1] 0x380

Timothy

Christopher

#include <iostream>#include <cstring>using namespace std;

// store 10 user names of up to 80 chars// names type is still char **char *names[10];

int main(){

char temp_buf[100];

cin >> temp_buf; // user enters “Timothy”names[0] = new char[strlen(temp_buf)+1];strcpy(names[0], temp_buf);

cin >> temp_buf; // user enters “Christopher”names[1] = new char[strlen(temp_buf)+1];strcpy(names[1], temp_buf);

return 0;}

Page 13: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

13

C++Strings

• Soyoudon'tlikerememberingallthesedetails?– Youcandoit!Don'tgiveup.

• C++providesa'string'classthatabstracts allthoseworrisomedetailsandencapsulates allthecodetoactuallyhandle:– Memoryallocationandsizing– Deepcopy– etc.

Page 14: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

14

ObjectSyntaxOverview

• You'vealreadyusedobjects– ifstream– string

• Caninitializeatdeclarationbypassinginitialvaluein()– Knownasaconstructor

• Usethedotoperatortocallanoperation(function)onanobjectoraccessadatavalue

• Somespecialoperatorscanbeusedoncertainobjecttypes(+,-,[],etc.)butyouhavetolookthemup

#include <iostream>#include <string>using namespace std;

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

// similar to char s1[] = "CS 103"string s1("CS 103");

// len will have 6int len = s1.size();

// s2 will have "103"string s2 = s1.substr(3,3);

// s3 will have "CS 103 is fun"string s3 = s1 + " is fun";

// will print 'C'cout << s1[0] << endl;return 0;

}

ifstream myfile(argv[1]);

myfile.fail();

myfile >> x;

String and Ifstreams are Examples of Objects

Page 15: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

15

StringExamples

• Must:– #include<string>– usingnamespacestd;

• Initializations/Assignment– Useinitializationconstructor– Use‘=‘operator– Canreassignandallmemoryallocation

willbehandled

• Redefinesoperators:– +(concatenate/append)– +=(append)– ==,!=,>,<,<=,>=(comparison)– [](accessindividualcharacter)

#include <iostream>#include <string>using namespace std;

int main(int argc, char *argv[]) {int len;string s1("CS 103");string s2 = "fun";

s2 = "really fun";

cout << s1 << " is " << s2 << endl;s2 = s2 + “!!!”;cout << s2 << endl;

string s3 = s1;if (s1 == s3){

cout << s1 << " same as " << s3;cout << endl;

}cout << “First letter is “ << s1[0];cout << endl;

}

CS 103 is really funreally fun!!! CS 103 same as CS 103First letter is C

Output:

http://www.cplusplus.com/reference/string/string/

Page 16: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

16

MoreStringExamples• Size/Lengthofstring• GetCString(char*)equiv.• Findasubstring

– Searchesforoccurrenceofasubstring– Returnseithertheindexwherethe

substringstartsorstring::npos– std::npos isaconstantmeaning‘just

beyondtheendofthestring’…it’sawayofsaying‘Notfound’

• Getasubstring– Passitthestartcharacterindexand

thenumberofcharacterstocopy– Returnsanewstring

• Others:replace,rfind,etc.

#include <iostream>#include <string>using namespace std;

int main(int argc, char *argv[]) {string s1("abc def");cout << "Len of s1: " << s1.size() << endl;

char my_c_str[80];strcpy(my_c_str, s1.c_str() );cout << my_c_str << endl;

if(s1.find("bc d") != string::npos)cout << “Found bc_d starting at pos=”:cout << s1.find(“bc_d”) << endl;

found = s1.find("def");if( found != string::npos){

string s2 = s1.substr(found,3)cout << s2 << endl;

}}

Len of s1: 7abc defThe string is: abc defFound bc_d starting at pos=1def

Output:

http://www.cplusplus.com/reference/string/string/

Page 17: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

17

Exercises

• http://bits.usc.edu/cs103/in-class-exercises/– Palindrome– CircularShift

Page 18: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

18

STRUCTSStartingwithdata…

Page 19: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

19

DefinitionsandInstances(Declarations)

• Objectsmustfirstbedefined/declared(asa'struct'or'class')– Thedeclarationisablueprintthatindicates

whatanyinstanceshouldlooklike– Identifiestheoverallnameofthestruct and

itsindividualcomponenttypesandnames– Thedeclarationdoesnotactuallycreatea

variable– Usuallyappearsoutsideanyfunction

• Thenanynumberofinstancescanbecreated/instantiatedinyourcode– Instances areactualobjectscreatedfromthe

definition(blueprint)– Declaredlikeothervariables

#include<iostream>

using namespace std;

// struct definitionstruct pixel {

unsigned char red;unsigned char green;unsigned char blue;

};// 'pixel' is now a type // just like 'int' is a type

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

int i,j;// instantiationspixel pixela;pixel image[256][256];// make pixela redpixela.red = 255;pixela.blue = pixela.green = 0;

// make a green imagefor(i=0; i < 256; i++){for(j=0; j < 256; j++){

image[i][j].green = 255;image[i][j].blue = 0;image[i][j].red = 0;

} }return 0;}

Page 20: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

20

MembershipOperator(.)• Eachvariable(andfunction)inanobject

definitioniscalleda‘member’oftheobject(i.e.struct orclass)

• Whendeclaringaninstance/variableofanobject,wegivetheentireobjectaname,buttheindividualmembersareidentifiedwiththemembernamesprovidedinthedefinition

• Weusethe.(dot/membership)operatortoaccessthatmemberinaninstanceoftheobject– Supplythenameusedinthedefinitionabove

sothatcodeisintheform:instance_name.member_name

#include<iostream>using namespace std;

enum {CS, CECS};

struct student {char name[80];int id;int major;

};

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

int i,j;// instantiationsstudent my_student;

// setting valuesstrncpy(my_student.name,”Tom Trojan”,80);

my_student.id = 1682942;my_student.major = CS;if(my_student.major == CECS)

cout << “You like HW” << endl;else

cout << “You like SW” << endl;...

return 0;}

Page 21: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

21

MemoryViewofObjects

• Eachinstantiationallocatesmemoryforallthemembers/componentsoftheobject(struct orclass)

Memory

0x010x020x030x040x05

0x00 00FF00FF0000

48C9

0x060x07

170x08…

pixela

image[0][0]

#include<iostream>

using namespace std;

struct pixel {unsigned char red;unsigned char green;unsigned char blue;};

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

int i,j;// instantiationspixel pixela;

pixel image[256][256];...

return 0;}

redgreenblue

image[0][1]

redgreenbluered

greenblue

Page 22: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

22

MemoryViewofObjects

• Objectscanhavedatamembersthatarearraysorevenotherobjects

Memory

0x01…

0x4F0x500x54

0x00 ‘T’‘o’…00

16829421

s1

#include<iostream>

using namespace std;

struct student {char name[80];int id;int major;

};

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

int i,j;// instantiationsstudent s1;...

return 0;}

name

idmajor

Page 23: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

23

IMPORTANTNOTESABOUTOBJECTS

Assignmentsemanticsandpointerstoobjects

Page 24: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

24

Objectassignment

• Considerthefollowinginitializationofs1

Memory

0x01…

0x4F0x500x54

0x00 ‘B’‘i’…0051

s1

#include<iostream>using namespace std;

enum {CS, CECS};

struct student {char name[80];int id;int major;

};

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

student s1,s2;strncpy(s1.name,”Bill”,80);

s1.id = 5; s1.major = CECS;

name

idmajor

Page 25: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

25

Objectassignment

• Assigningoneobjecttoanotherwillperformanelementbyelementcopyofthesourcestruct tothedestinationobject

Memory

0x01…

0x4F0x500x54

0x00 ‘B’‘i’…0051

s1

#include<iostream>using namespace std;

enum {CS, CECS };

struct student {char name[80];int id;int major;

};

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

student s1,s2;strncpy(s1.name,”Bill”,80);

s1.id = 5; s1.major = CECS;s2 = s1;

return 0;}

name

idmajor

‘B’‘i’…0051

name

idmajor

s2

Page 26: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

26

PointerstoObjects

• Wecandeclarepointerstoobjectsjustasanyothervariable

Memory

0x101…

0x14F0x1500x154

0x100 ‘B’‘i’…0051

s1

#include<iostream>using namespace std;

enum {CS, CECS };

struct student {char name[80];int id;int major;

};

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

student s1, *stu_ptr;strncpy(s1.name,”Bill”,80);

s1.id = 5; s1.major = CECS;stu_ptr = &s1;

return 0;}

name

idmajor

0x100

stu_ptr

Page 27: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

27

AccessingmembersfromaPointer

• Candereferencethepointerfirstthenusethedotoperator

Memory

0x101…

0x14F0x1500x154

0x100 ‘B’‘i’…0051

#include<iostream>using namespace std;

enum {CS, CECS };

struct student {char name[80];int id;int major;

};

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

student s1,*stu_ptr;strncpy(s1.name,”Bill”,80);

s1.id = 5; s1.major = CECS;stu_ptr = &s1;(*stu_ptr).id = 4;strncpy( (*stu_ptr).name, “Tom”,80);

return 0;}

0x100

Memory

0x101…

0x14F0x1500x154

0x100 ‘T’‘o’…0041

0x100

Page 28: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

28

Arrow(->)operator• Savekeystrokes&havecleanerlookingcodebyusingthearrow

(->)operator– (*struct_ptr).member equivalenttostruct_ptr->member– Alwaysoftheform:ptr_to_struct->member_name

Memory

0x101…

0x14F0x1500x154

0x100 ‘B’‘i’…0051

#include<iostream>using namespace std;

enum {CS, CECS };

struct student {char name[80];int id;int major;

};

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

student s1,*stu_ptr;strncpy(s1.name,”Bill”,80);

s1.id = 5; s1.major = CECS;stu_ptr = &s1;stu_ptr->id = 4;strncpy( stu_ptr->name, “Tom”,80);

... return 0;}

0x100

Memory

0x101…

0x14F0x1500x154

0x100 ‘T’‘o’…0041

0x100

Page 29: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

29

PassingObjectsasArguments• InC,argumentsmustbeasingle

value[i.e.asingledataobject/can’tpassanentirearrayofdata,insteadpassapointer]

• Objectsaretheexception…youcanpassanentirestruct ‘byvalue’– Willmakeacopyofthestruct and

passittothefunction• Ofcourse,youcanalwayspassa

pointer[especiallyforbigobjectssincepassbyvaluemeansmakingacopyofalargeobjects]

#include<iostream>

using namespace std;

struct Point {int x;int y;

};

void print_point(Point myp){

cout << “(x,y)=“ << myp.x << “,” << myp.y;cout << endl;

}

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

Point p1;p1.x = 2; p1.y = 5;print_point(p1);

return 0;}

Page 30: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

30

ReturningObjects

• Canonlyreturnasinglestruct fromafunction[i.e.notanarrayofobjects]

• Willreturnacopy ofthestruct indicated– i.e.'return-by-value'

#include<iostream>

using namespace std;struct Point {

int x;int y;

};void print_point(Point *myp){

cout << “(x,y)=“ << myp->x << “,” << myp->y;cout << endl;

}Point make_point(){

Point temp;temp.x = 3; temp.y = -1;

return temp;}int main(int argc, char *argv[]){

Point p1;p1 = make_point(); print_point(&p1);

return 0;}

Page 31: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

31

ENUMERATIONS

Page 32: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

32

Enumerations

• Associatesaninteger(number)withasymbolicname

• enum [optional_collection_name] {Item1, Item2, … ItemN}

– Item1=0– Item2=1– …– ItemN =N-1

• Usesymbolicitemnamesinyourcodeandcompilerwillreplacethesymbolicnameswithcorrespondingintegervalues

const int BLACK=0;const int BROWN=1;const int RED=2;

const int WHITE=7;

int pixela = RED;int pixelb = BROWN;...

// First enum item is associated with 0enum Colors {BLACK,BROWN,RED,...,WHITE};

int pixela = RED; // pixela = 2;int pixelb = BROWN; // pixelb = 1;

Hard coding symbolic names with given codes

Using enumeration to simplify

Page 33: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

33

TYPEDEF'SAliasesforatypename

Page 34: CS 103 Unit 9 – Objects, Structs, and Stringsbytes.usc.edu/files/cs103/slides/Unit9_Objects.pdf · • Often these abstract types can be represented as a collection of integers,

34

typedef’s• Oftenwedonotwanttoalwaystypesomuchtodeclarean

instanceofastruct• typedefs allowustocreatean‘alias’foradata-type.• Format:

typedef official_type alias_name• Examples:

typedef int score_t;typedef double decimal_t;//xisreallyanint,yisreallyadoublescore_t x;decimal_t y;

• Canbeusedtomaketheuseofvariablesmoreobvious– Imagineyouhadafewint's beingusedasscoresandmanyotherints

elsewhere…thenyouhavetochangeallscorevariablestodoubles.Youcan'tjustfind..replace allints todoubles.