24
CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang [email protected] www.cs.ucla.edu/~swyang

CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang [email protected] swyang

  • View
    219

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

CS31: Introduction to Computer Science I

Discussion 1A 5/28/2010

Sungwon [email protected]

www.cs.ucla.edu/~swyang

Page 2: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Quick Review• What did we learn last week

– Dynamic Memory Allocation• can create storage space dynamically in the area of heap• new operator is used to declare dynamic variables• new operator returns the address of memory allocated

– Dynamic Array Declaration• can use int variables for the array size• returns the address of the first item of an array

– Creation & Destruction• dynamic variables created by new operator and destroyed by delete operator• if creation fails, NULL will be returned• need to manually destroy variables after using them to avoid memory leakage• need to be careful not to lose the pointers that refer to the dynamic variables

Page 3: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

types of variables• Variable types we have seen so far– int : integer numbers– double : numbers with decimal point– char : single character – string : multiple characters– bool : boolean variables (true or false)– etc…

• Can we group multiple variable types into a single entity and define our own variable type?– arrays do not work, because all the items of an array must

be the same type.

Page 4: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Structs

• A C/C++ struct is an aggregate data type of multiple data items which can hold items of different types

• The definition of a struct specifies the names and types of its member elements– Each member element has a unique name and a type– Member elements can be any type of C++ data

including simple variables, arrays, and even other structs

Page 5: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Structs• suppose that we manage student list

– need to manage student name, ID, email address, and grade.

int main (){ //struct definition struct Student { string name; int id; string email; char grade; };

const int NUM_STUDENTS = 25; //struct instance declaration Student st[NUM_STUDENTS]; …}

int main(){ const int NUM_STUDENTS = 25; string names[NUM_STUDENTS]; int ids[NUM_STUDENTS]; string emails[NUM_STUDENTS]; char grades[NUM_STUDENTS]; … …}

Page 6: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Struct Member Access• using period(.)

struct Student{ string name; int id; string email; char grade;};

int main() { const int NUM_STUDENTS = 25; Student st[NUM_STUDENTS];

st[0].name = "Sungwon Yang"; st[0].id = 703650142; st[0].email = "[email protected]"; st[0].grade = 'A';

cout << st[0].name << endl; cout << st[0].id << endl; cout << st[0].email << endl; cout << st[0].grade << endl;}

Page 7: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Structs Copy• simply can use = operatorint main(){ const int NUM_STUDENTS = 25; Student st[NUM_STUDENTS];

st[0].name = "Sungwon Yang"; st[0].id = 703650142; st[0].email = "[email protected]"; st[0].grade = 'A';

st[1] = st[0];

cout << st[1].name << endl; cout << st[1].id << endl; cout << st[1].email << endl; cout << st[1].grade << endl;}

Sungwon [email protected]

Page 8: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Structs Initialization

• similar to the initialization of an array

int main(){ Student st1; //assignment st1.name = "Sungwon Yang"; st1.id = 703650142; st1.email = "[email protected]"; st1.grade = 'A';

//initialization Student st2 = {"John Smith", 123456789, "[email protected]", 'F'};

//rest member variables will be set to zero value Student st3 = {"David Smallberg"};}

Page 9: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Struct and Functions

• Struct instances can be function parameters– can be passed either by value or reference– can be passed by pointers

• Struct can be return value of a function

Page 10: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Struct Member Access thru Pointer• using -> operator– can also use dereferencing operator “*” and “.”

Student *st = new Student;

st->name = "Agent Smith";st->id = 999999999;st->email = "[email protected]";st->grade = 'A';

cout << st->name << endl;cout << st->id << endl;cout << (*st).email << endl;cout << (*st).grade << endl;// *st.grade is equivalent to *(st.grade)

struct Student{ string name; int id; string email; char grade;};

Page 11: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Classes• similar to Struct

– can group multiple variable types into a single entity

• In C++, structs and classes are technically identical– Classes can have member functions in addition to member

variables• Although technically allowed, member functions are by convention

not usually included in structs

– Classes can give attribute to members• members of a class can be either private or public• A class and a struct are mechanically identical except that by default

members of a struct are public and members of a class are private

Page 12: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Classes• start with simple example!

class Cat //by convention, use capital{public: //followings are set to public int m_age; //member data void meow(); //member function };

//scope resolution operator (::) separates the class and function namesvoid Cat::meow(){ cout << "Meow~~ " << endl; m_age++;}

int main(){ Cat kitty1; //create cat instance Cat kitty2; //kitty1, kitty2 object name

kitty1.m_age = 1; //use object name kitty2.m_age = 3; // not class name

kitty1.meow();

cout << kitty1.m_age << endl; cout << kitty2.m_age << endl;}

Meow~~23

Page 13: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Classes

• public vs. private members– public members (data and functions) can be

accessed in any other functions (including main function)

– private members can be accessed only within the same class• in main function, other functions, or other classes, we

cannot access the private members

Page 14: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Classes• private members

class Cat{public: //followings are set to public void meow(); private: //followings are set to private int m_age;};

//scope resolution operator (::) separates the class and function namesvoid Cat::meow(){ cout << "Meow~~ " << endl; m_age++;}

int main(){ Cat kitty1; //create cat instance Cat kitty2; //kitty1, kitty2 object name

kitty1.m_age = 1; //ERROR kitty2.m_age = 3; //ERROR

kitty1.meow();

cout << kitty1.m_age << endl; //ERROR cout << kitty2.m_age << endl; //ERROR}

Page 15: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Classes

• How can access private members?– need Accessors and Mutators

• An accessor is a function that returns the value of a data member of a class

• A mutator is a function that sets the value of a data member of a class

Page 16: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Accessor and Mutatorclass Cat{public: //followings are set to public void meow(); int getAge(); //can be called in other functions void setAge( int age);private: //followings are set to private int m_age;};

void Cat::meow(){ cout << "Meow~~ " << endl; m_age++;}// function that returns cat’s ageint Cat::getAge(){ return m_age;}// function that sets cat’s agevoid Cat::setAge(int age){ m_age = age;}

int main(){ Cat kitty1; Cat kitty2;

kitty1.setAge(1); //call setAge() function kitty2.setAge(2);

kitty1.meow();

// call getAge() function cout << kitty1.getAge() << endl; cout << kitty2.getAge() << endl; }

Meow~~23

Page 17: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Constructors• how can initialize class objects?

class Cat{public: // default constructor, // should be the same as the class name. Cat(); void meow(); int getAge(); void setAge( int age);private: int m_age;};

// constructor has no return typeCat::Cat(){ // when created, the age is set to 0 setAge(0); // or m_age = 0; cout << "A cat is born" << endl;}

int main(){ Cat kitty1; // no parenthesis () Cat kitty2;

// call getAge() function cout << kitty1.getAge() << endl; cout << kitty2.getAge() << endl; }

A cat is bornA cat is born00

Page 18: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Constructors• can have multiple constructors (overloading)

class Cat{public: Cat(); // default constructor Cat( int initAge); // constructor with parameter void meow(); int getAge(); void setAge( int age);private: int m_age;};

Cat::Cat(){ // when created, the age is set to 0 setAge(0); cout << "A cat is born" << endl;}

Cat::Cat( int initAge){ // when createdm the age is set to initAge setAge( initAge); cout << "A cat is born" << endl;}

int main(){ Cat kitty1; Cat kitty2(5);

// call getAge() function cout << kitty1.getAge() << endl; cout << kitty2.getAge() << endl; }

A cat is bornA cat is born05

Page 19: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Initialization List• suppose that we have more variables need to be initialized

– which one does look better? It is your choice!class Cat{public: Cat(); void meow(); int getAge(); void setAge( int age);private: int m_age; int m_weight; int m_height; int gender; // 1 if male, 2 if female};

Cat::Cat(){ m_age = 0; m_weight = 100; m_height = 10; m_gender = 1; cout << "A cat is born" << endl;}

class Cat{public: Cat(); void meow(); int getAge(); void setAge( int age);private: int m_age; int m_weight; int m_height; int gender; // 1 if male, 2 if female};

Cat::Cat(): m_age(0) , m_weight(100) , m_height(10) , m_gender(1){ cout << "A cat is born" << endl;}

Page 20: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Class Member Access thru Pointers

• similar to struct– use -> operator

int main(){ Cat kitty1; Cat kitty2(5);

// call getAge() function cout << kitty1.getAge() << endl; cout << kitty2.getAge() << endl; }

int main(){ Cat *kitty1 = new Cat; Cat *kitty2 = new Cat(5);

// call getAge() function cout << kitty1-> getAge() << endl; cout << kitty2-> getAge() << endl; }

Page 21: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Destructors• called when class object is destroyed

class Cat{public: Cat(); //destructor, no return value, no arguments ~Cat(); void meow(); int getAge(); void setAge( int age);private: int m_age;};

// destructor has no return typeCat::~Cat(){ // execute following codes when destroyed cout << "R.I.P." << endl; // if this class creates dynamic variables, // delete operator need to be used here}

int main(){ Cat *kitty1 = new Cat; Cat *kitty2 = new Cat(5);

// call getAge() function cout << kitty1-> getAge() << endl; cout << kitty2-> getAge() << endl;

delete kitty1; delete kitty2; }

A cat is bornA cat is born05R.I.PR.I.P

Page 22: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

const Keyword in class function• To prevent change to a reference parameter, the

keyword const is included before the parameter name– e.g. void fct1(const int& param);– The compiler will then detect an error if the variable param is

assigned a value

• To prevent change to a class function, the keyword const is included after the member list

– e.g. void fct2() const;– The compiler will then detect an error if the function changes

any of the member data– If a class object is passed into a function with const keyword,

the members of the class cannot be changed

Page 23: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

const Keyword• project #7 warm-up

class Pet { public:

Pet(string nm, int initialHealth); void eat(int amt); void play(); string name() const; int health() const; bool alive() const;

private: string m_name; int m_health;

};

string Pet::name() const { m_name = "Brian" ; //ERROR return m_name; }

string Pet::health () const { m_health = 0 ; //ERROR return m_health; }

string Pet::alive () const { m_health++; //ERROR if(m_health > 0)

return true; else

return false;}

Page 24: CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang swyang@cs.ucla.edu swyang

Structs vs. Classes

Structures are remnants of C, and in C++. Originally, structures could not have member functions -- its sole purpose was to group variables. As the paradigm of Object Oriented Programming emerged, classes were introduced, and structures in C are just a special case of classes (i.e. classes with public member variables and nothing else).

The only difference between classes and structures is that, if you declare a member without indicating the publicness/privateness of it, it will be considered public in a structure, and private in a class. In most cases, you won’t see that many cases where structures are used to represent an object, as most people just use classes. Structures are mostly used to serve their original purpose of grouping related variables.