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

Slides:



Advertisements
Similar presentations
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Introduction to Programming Lecture 39. Copy Constructor.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Writing a Good Program 5. Objects and Classes in C++
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Templates Zhen Jiang West Chester University
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Pointers Pointer a data type stores a memory address points to whatever the memory location contains A pointer is a variable that can store a memory address.
CPS120: Introduction to Computer Science
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Agenda Object Oriented Programming Reading: Chapter 14.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
More C++ Features True object initialisation
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
11 Introduction to Object Oriented Programming (Continued) Cats.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Pointer to an Object Can define a pointer to an object:
Discussion 1E Jie(Jay) Wang Week 10 Dec.2.
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
CS31 Discussion Jie(Jay) Wang Week8 Nov.18.
Introduction to Classes
Memberwise Assignment / Initialization
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Java Programming Language
CS31 Discussion 1H Winter19: week 9
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
CS31 Discussion 1H Fall18: week 9
9-10 Classes: A Deeper Look.
Presentation transcript:

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

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

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.

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

Structs suppose that we manage student list – need to manage student name, ID, address, and grade. int main () { //struct definition struct Student { string name; int id; string ; 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 s[NUM_STUDENTS]; char grades[NUM_STUDENTS]; … }

Struct Member Access using period(.) struct Student { string name; int id; string ; char grade; }; int main() { const int NUM_STUDENTS = 25; Student st[NUM_STUDENTS]; st[0].name = "Sungwon Yang"; st[0].id = ; st[0]. = st[0].grade = 'A'; cout << st[0].name << endl; cout << st[0].id << endl; cout << st[0]. << endl; cout << st[0].grade << endl; }

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 = ; st[0]. = st[0].grade = 'A'; st[1] = st[0]; cout << st[1].name << endl; cout << st[1].id << endl; cout << st[1]. << endl; cout << st[1].grade << endl; } Sungwon Yang A

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

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

Struct Member Access thru Pointer using -> operator – can also use dereferencing operator “*” and “.” Student *st = new Student; st->name = "Agent Smith"; st->id = ; st-> = st->grade = 'A'; cout name << endl; cout id << endl; cout << (*st). << endl; cout << (*st).grade << endl; // *st.grade is equivalent to *(st.grade) struct Student { string name; int id; string ; char grade; };

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

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

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

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 }

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

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

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

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

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

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

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

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

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

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.