Lecture 03a: C++ classes Topics: basic classes and objects constructor, destructor Miscellaney An intro to the STL (Standard Template Library)

Slides:



Advertisements
Similar presentations
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.
Advertisements

Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
CS31: Introduction to Computer Science I Discussion 1A 5/28/2010 Sungwon Yang
Lecture 9 Concepts of Programming Languages
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
(…A FEW OF THEM) C++ DESIGN PATTERNS. WHAT ARE THEY? Commonly occurring constructs Could be part of good software engineering Not universally agreed Good.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Pointer Data Type and Pointer Variables
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
February 11, 2005 More Pointers Dynamic Memory Allocation.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Object-Oriented Programming in C++
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
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 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
11 Introduction to Object Oriented Programming (Continued) Cats.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
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:
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
11 Introduction to Object Oriented Programming (Continued) Cats.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
C++ Functions A bit of review (things we’ve covered so far)
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
“Generic Programming” ECE 297
Procedural and Object-Oriented Programming
Learning Objectives Pointers as dada members
Lecture 04: Sequences structures
Motivation and Overview
C++ Object-Oriented Programming
Introduction to Classes
Dynamic Memory CSCE 121 J. Michael Moore.
group work #hifiTeam
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Pointers, Dynamic Data, and Reference Types
Dynamic Memory CSCE 121.
Presentation transcript:

Lecture 03a: C++ classes Topics: basic classes and objects constructor, destructor Miscellaney An intro to the STL (Standard Template Library)

Overview A way to combine – Data (attributes, or member variables) We had this in struct’s – Behaviors (methods, or member functions) We didn’t have this in struct’s Very natural way to program… – …for some people – …after you get past the learning curve

Part I: Basic Classes and Objects Two parts: – Class design Not necessary if using someone else's class (e.g. SDL) Designing a blueprint for a new type – Make instances (objects) of a class Each shares the common structure defined by the class… …but has it's own copy of the attributes Sound familiar? – We've seen this with C structs – …struct's are a limited form of classes classes can do everything struct's can, but not vice-versa

Basic example // Basically a struct class Monster { public: int hp; char name[16]; }; int main() { Monster m1, m2; m1.hp = 100; m2.hp = 50; strcpy(m1.name, “Ogre“); // string.h included strcpy(m2.name, "Goblin“); cout << m1.name << " has " << m1.hp << "hp" << endl; }

Basic Example…add methods class Monster { public: int hp; char name[16]; void takeDamage(int amt)// an inline method { hp = hp – amt < 0 ? 0 : hp – amt; cout << "Ouch!" << endl; } void heal();// method prototype }; void Monster::heal()// non-inline method definition { hp = 100; cout << "Ahhhh" << endl; } int main() { Monster m1, m2; m1.hp = 100; m2.hp = 50; strcpy(m1.name, "Ogre“); strcpy(m2.name, "Goblin“); m1.takeDamage(5); cout << m1.name << " has " << m1.hp << "hp" << endl; m1.heal(); }

Basic Example…add methods void Monster::heal() // non-inline method definition { hp = 100; cout << "Ahhhh" << endl; } All instances have their own copy of attributes (see the first version of main) All instances share the same object code for methods. So…on the line "hp = 100;", whose hp is changing? – The answer involves the keyword this.

this Any time a method of an object is called: – The normal registers, parameters, etc. are created on the stack. – In addition, a pointer to the calling object is put on the stack as well (this). These 3 lines are all equivalent hp = 100;// as it is on prev. slide (*this).hp = 100;// de-reference this this->hp = 100;// shorthand for above [Show the stack on prev. example]

Part II: Constructors / Destructors [Motivation] Called automatically when: – constructor: a new instance is made – destructor: an instance is destroyed When stack-based variables go out of scope When heap-based data is deallocated Uses of constructor – Guarantee that all data has been initialized – Run any "startup" code Uses of destructor – Run an cleanup code – Often: de-allocate memory

Constructors / Destructors, cont. Both the constructor and destructor look like functions – No return values, though. – Name must be exactly the same as the class – Destructor has a tilde (~) before it. In the constructor, you can [slightly quicker] initialize your attributes using the colon operator You can overload the constructor (have multiple versions)

Constructor / Destructor example class Sprite { public: Sprite(); // "Default" constructor Sprite(char * fname);// "Loader" constructor ~Sprite();// Destructor int load(char * fname); protected: SDL_Surface * mSurf; int mWidth, int mHeight; }; Sprite::Sprite() : mSurf(NULL), mWidth(-1), mHeight(-1) { } Sprite::Sprite(char * fname) { mSurf = NULL;// Possibly a bit slower than using colon op. mWidth = -1; mHeight = -1; load(fname); }

Constructor / Destructor example Sprite::~Sprite() { if (mSurf) SDL_FreeSurface(mSurf); } int Sprite::load(char * fname) { mSurf = SDL_LoadBMP(fname); if (mSurf) { mWidth = mSurf->w; mHeight = mSurf->h; return 1; } return 0; }

III. Miscellaney Class (static) attributes and methods – "Normal" attributes are instance attributes Each instance has its own copy – "Normal" methods are shared by all instances, but this is passed so we can access instance attributes – Static attributes are shared by all instances (only one copy per class) We can have a static attribute without any instances! – Static methods are also shared, but don't have a this parameter We don't have access to normal attributes

Static's example // Monster.h #ifndef _MONSTER_H_ #define _MONSTER_H_ #include using namespace std; class Monster { protected: int mScariness; // A normal (instance) attribute static int msNumInstances; // A static (class) attribute public: Monster(int slvl); // A normal (instance) method ~Monster(); // A normal (instance) method void roar(); // A normal (instance) method static int getNumInstances(); // A static (class) method }; #endif

Static's example, cont. // Monster.cpp #include "Monster.h" int Monster::msNumInstances = 0; // Note the static variables initialization Monster::Monster(int slvl) : mScariness(slvl) { msNumInstances++; // Note: We can access static attributes in // a normal method } Monster::~Monster() { msNumInstances--; } void Monster::roar() { cout << "ROAR"; for (int i = 0; i < mScariness; i++) cout << "!"; cout << endl; } int Monster::getNumInstances()// Note: don't put static keyword in the.cpp file { // cout << mScariness << endl; // Error. Can’t access non-static’s return msNumInstances; }

Static's example, cont. // main.cpp #include "Monster.h" int main() { cout << "#Monsters = " << Monster::getNumInstances() << endl; // cout << Monster::msNumInstances << endl; // Not allowed b/c // msNumInstances is protected Monster m1(5); Monster m2(7); Monster * mp; m1.roar(); m2.roar(); mp = new Monster(10); cout << "#Monsters = " << Monster::getNumInstances() << endl; mp->roar(); delete mp; cout << "#Monsters = " << Monster::getNumInstances() << endl; }

enum [Nothing to do with classes] An integer, basically. When defining the enum type, you can specify the values which can be assigned – a word (more descriptive than a number)

enum example // Somewhere else (maybe in a.h file) enum Day {monday, tuesday, wednesday, thursday, friday, saturday, sunday}; int main() { Day d; d = wednesday; cout << d << endl;// 2 //d = funday;// Error //d = 18;// Error //d++;// Error d = (Day)((int)d + 1); cout << d << endl;// 3 d = (Day)55;// Allowed in VC2012, but a bad idea... cout << d << endl; }

IV. STL Intro Standard Template Library Uses templates (we'll touch on these later) – I'll treat this part as "magic" for now… A relatively new addition to C++ Automates a lot of tedious tasks that we do a lot. Makes it more "Python"-ish. Internally, though, it uses tools we've seen already We'll look at vectors for now. Others include: – [linked] lists – maps (similar to python dictionaries) – sets –…–…

Vectors A "dynamic" array Behind the scenes, just an array – With the current max and used size. Can add and remove – Adds at the end are OK – in the middle they're very slow. – Similar for removes Includes code to grow the array if we add more than max – Really, re-allocates it on the heap (larger), copies existing data (SLOW!) Supports array-indexing (through operator overloading)

Vector example #include using namespace std; int main() { vector vint; vector vstr; unsigned int i; vint.push_back(5); vint.push_back(7); vint.push_back(13); cout << "Vint contents" << endl << "=============" << endl; for (i=0; i<vint.size(); i++) cout << i << "\t" << vint[i] << endl; vint.pop_back(); vint.insert(vint.begin() + 1, 99); // Inserts at pos#1, moves everything 'down' cout << "Vint contents" << endl << "=============" << endl; for (i=0; i<vint.size(); i++) cout << i << "\t" << vint[i] << endl;

Vector example, cont. vint.resize(7); cout << "Vint contents" << endl << "=============" << endl; for (i=0; i<vint.size(); i++) cout << i << "\t" << vint[i] << endl; cout << "Current max: " << vint.max_size() << endl; vint.clear(); cout << "Vint size: " << vint.size() << endl; // All the same operations are proved for strings (or any type) vstr.push_back("ABC"); vstr.push_back("XYZ"); //vstr.push_back(9);// ERROR! }