Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang

Similar presentations


Presentation on theme: "CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang"— Presentation transcript:

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

2 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

3 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.

4 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

5 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]; … }

6 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 = "swyang@cs.ucla.edu"; st[0].grade = 'A'; cout << st[0].name << endl; cout << st[0].id << endl; cout << st[0].email << endl; cout << st[0].grade << endl; }

7 Structs Copy simply can use = operator int main() { const int NUM_STUDENTS = 25; Student st[NUM_STUDENTS]; st[0].name = "Sungwon Yang"; st[0].id = 703650142; st[0].email = "swyang@cs.ucla.edu"; 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 Yang 703650142 swyang@cs.ucla.edu A

8 Structs Initialization similar to the initialization of an array int main() { Student st1; //assignment st1.name = "Sungwon Yang"; st1.id = 703650142; st1.email = "swyang@cs.ucla.edu"; st1.grade = 'A'; //initialization Student st2 = {"John Smith", 123456789, "john@.cs.ucla.edu", 'F'}; //rest member variables will be set to zero value Student st3 = {"David Smallberg"}; }

9 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

10 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 = "smith@matrix.com"; st->grade = 'A'; cout name << endl; cout 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; };

11 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

12 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 names void 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~~ 2 3

13 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

14 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 names void 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 }

15 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

16 Accessor and Mutator class 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 age int Cat::getAge() { return m_age; } // function that sets cat’s age void 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~~ 2 3

17 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 type Cat::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 born 0

18 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 born 0 5

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

20 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 getAge() << endl; }

21 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 type Cat::~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 getAge() << endl; delete kitty1; delete kitty2; } A cat is born 0 5 R.I.P

22 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

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

24 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.


Download ppt "CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang"

Similar presentations


Ads by Google