System Programming. Practical Session 9. C++ classes
|
|
- Godfrey Russell
- 6 years ago
- Views:
Transcription
1 System Programming Practical Session 9 C++ classes
2 C++ parameter passing void incval(int n) { //By value n++; void incpoint(int *p) { //By pointer *p = 5; p = 0; void incref(int &n) { //By Reference cout << "incref: n = " << n << endl; cout << "incref: &n = " << &n << endl; n++; Printout main: &x = 0xbfab547c main: x2 = 2 main: &x2 = 0xbfab547c x = 2 *q = 5 incref: n = 5 incref: &n = 0xbfab547c x = 6 int main(int argc, char *argv[]) { int x = 2; int &x2 = x; cout << "main: &x = " << &x << endl; //main: &x = 0xbfab547c cout << "main: x2 = " << x2 << endl; //main: x2 = 2 cout << "main: &x2 = " << &x2 << endl; //main: &x2 = 0xbfab547c incval(x); cout << "x = " << x <<endl; //x = 2 (and not 3!) int *q = &x; incpoint(q); cout << "*q = " << *q <<endl; //*q = 5 incref(x); cout << "x = " << x << endl; //x = 6
3 C++ STL examples - Vector void clean_odd(std::vector<int> &vec) { std::vector<int>::iterator iter = vec.begin(); while (iter!= vec.end()) { if (*iter % 2 == 0) { iter++; else { iter = vec.erase(iter); int main(int argc, char *argv[]) { std::vector<int> vec; vec.push_back(0); vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); Printout clean_odd(vec); for (std::vector<int>::iterator iter = vec.begin(); iter!= vec.end(); ++iter){ std::cout << *iter << std::endl; return 0;
4 C++ STL examples - Map int main(int argc, char *argv[]) { std::map<std::string,int> stringcounts; std::string str; std::vector<string> vec; vec.push_back("abc"); vec.push_back("123"); vec.push_back("qaz"); vec.push_back("789"); vec.push_back("abc"); vec.push_back("123"); Printout word: 123, count: 2 word: 789, count: 1 word: abc, count: 2 word: qaz, count: 1 std::vector<string>::iterator veciter = vec.begin(); while (veciter!= vec.end()) { std::map<std::string,int>::iterator found = stringcounts.find(*veciter); if (found!= stringcounts.end()) { found->second++; else { stringcounts.insert(std::make_pair(*veciter, 1)); veciter++; std::map<std::string,int>::iterator iter; for( iter = stringcounts.begin(); iter!= stringcounts.end(); ++iter) { std::cout << "word: " << iter->first << ", count: " << iter->second << std::endl; return 0;
5 C++ STL examples - Priority Queue class Cow { private: int _id; public: Cow(int id) : _id(id) { ; int getid() const { return _id; // A comparator is a class that implements the operator() // It is passed as a parameter to the priority queue // and used to perform the comparisons among items in the queue. class CowComparator { public: bool operator()(const Cow &x, const Cow &y) { // return true if x < y, false otherwise return x.getid() < y.getid(); ; int main(int argc, char *argv[]) { typedef std::priority_queue<cow, std::vector<cow>, CowComparator> PrioQueue; PrioQueue queue; queue.push(cow(0)); queue.push(cow(3)); queue.push(cow(1)); queue.push(cow(2)); Printout while (!queue.empty()) { std::cout << queue.top().getid() << std::endl; queue.pop();
6 Outline Basic concepts Classes that hold pointers Destructor Copy constructor Operator=
7 C++ simple class example // THE DECLARATION FILE OF THE CLASS POINT (Point.h) class Point { public: Point(); Point(double xval, double yval); void move(double dx, double dy); double getx() const; //const functions do not change the state of an object double gety() const; private: double _x; double _y; ; // semicolon at the end of the class declaration - const functions do not change the state of an object - const functions cannot modify const data. - when const functions return references or pointers to members of the class, they must also be const. - const methods can only access const methods.
8 C++ simple class example // THE IMPLEMENTATION FILE OF CLASS POINT (Point.cpp) #include "Point.h" Point::Point():_x(0), _y(0){ //The :: operator separates class name and method name Point::Point(double xval, double yval):_x(xval),_y(yval){ void Point::move(double dx, double dy) { _x = _x + dx; _y = _y + dy; double Point::getX() const { //const functions do not change the state of an object return _x; double Point::getY() const { return _y;
9 C++ simple class example Use example //Once a variable declared as const, one can only use methods declared const on that variable #include <iostream> #include point.h int main( ){ Point p(0,0); //Point p; p.move(10,15); std::cout << p.getx() << std::endl; std::cout << p.gety() << std::endl; const Point p2(20,12); // p2.move(1,1); compilation error since move is not declared const std::cout << p2.getx() << std::endl; std::cout << p2.gety() << std::endl;
10 Member Initialization List // THE DECLARATION class Circle{ ; public: Circle(); Circle(double centerx, double centery, double radius); private: Point _center; double _radius; // THE IMPLEMENTATION Circle::Circle(): _center(0,0), _radius(1) { //default constructor Circle::Circle(double centerx, double centery, double radius): _center(centerx, centery), _radius(radius) {
11 Member Initialization List Example: Circle::Circle(): _center(0,0), _radius(1) { Rules The initial value can be any expression. The order the initialization happens is according to the order the member variables are declared. The member initialization list is executed before the body of the constructor. Not initializing a member (class object) via the initialization list means implicitly calling its default constructor Const members of a class can only be initialized via member initialization list.
12 Syntax: class Derived : public Base { ; Inheritance #include point.h #include color.h // suppose that we have defined class Color class Pixel : public Point{ //instead of extends in Java Color _color; ; Pixel::Pixel(Point point, Color color) : Point(point), _color(color) { // example of a derived constructor calling the base constructor // Syntax: Derived::Derived(.) : Base(.) { // instead of super in Java
13 -<Operator Shortcut for accessing members of an object pointed by a pointer. ptr->member is a shortcut for (*ptr).member class Point{... int main( ){ Point *p1=new Point(0,0); Point p2(0,0); p1->getx(); (*p1).getx(); p2.getx(); (&p2)->getx();
14 Objects In C++, object variables hold values, not object references. When one object is assigned to another, a copy of the actual values is made. When modifying an object in a function, you must remember to use call by reference. Two object variables cannot jointly access one object. If you need this effect in C++, then you need to use pointers/references An object variable can only hold values of a particular type. If you want a variable to hold objects from different subclasses, you need to use pointers. If you want a variable point to either null or to an actual object, then you need to use pointers in C++.
15 The "this" Pointer Note that, as in Java, this is a pointer to the active object. So for example, when: L1 = L2 is executed, L1's member function operator= is called, so this is a pointer to L1. We also make use of this for the returned value in the operator=. the type to be returned is List& so we dereference this, a.k.a return *this. We would like to establish a way to distinguish between parameters and class variables. This can be done by the "this" pointer. It used as a pointer to the class object instance by the member functions. this pointer stores the address of the object instance, to enable pointer access of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.
16 Classes that hold pointers A class that has a pointer data member should include the following member functions: 1. A virtual destructor 2. A copy constructor 3. operator= (assignment)
17 Linked List Example Link data_ next_ List head_ data_ next_ data_ next_
18 Link class Link { private: Link* next_; std::string data_; public: Link(const std::string& data, Link* link); Link(const Link& alink); //copy constructor virtual ~Link(); // destructor void setnext(link* link); Link* getnext() const; const std::string& getdata() const; ;
19 Link Link::Link(const std::string& data, Link* link) : data_(data) { setnext(link); void Link::setNext(Link* link) { next_=link; Link* Link::getNext() const { return next_; const std::string& Link::getData() const { return data_; Link::~Link() { Link::Link(const Link& alink) { Data_= alink.getdata(); Next_= 0; // destructor // copy constructor
20 List class List { private: Link* head_; Link* copy() const; void clear(); public: List(); const Link* gethead() const; void insertdata(const std::string& data); void removefirst(); ; List(const List& alist); virtual ~List(); List& operator=(const List &L);
21 List::List() : head_(0) { List //Constructor, Builds an empty list const Link* List::getHead() const{ return head_; void List::insertData(const std::string& data){ head_ = new Link(data, head_); Before (insertdata(...) ): data_ next_ data_ next_ 0 Current head_ After (insertdata(...) ): data_ next_ data_ next_ data_ next_ 0 Current head_ Old head_
22 List List::List() : head_(0) { //Constructor, Builds an empty list const Link* List::getHead() const{ return head_; void List::insertData(const std::string& data){ head_ = new Link(data, head_); void List::removeFirst(){ //removes the current head if (0!= head_) { Link* tmp = head_; head_ = head_->getnext(); delete tmp; Before deleting tmp (removefirst): data_ next_ data_ next_ data_ next_ 0 tmp head_->getnext()
23 List List::List() : head_(0) { //Constructor, Builds an empty list const Link* List::getHead() const{ return head_; void List::insertData(const std::string& data){ head_ = new Link(data, head_); void List::removeFirst(){ //removes the current head if (0!= head_) { Link* tmp = head_; head_ = head_->getnext(); delete tmp; List::~List() { clear(); //Destructor: "deep delete" void List::clear(){ while (0!= head_) { removefirst(); //Clear all content (delete all links)
24 Link* List::copy() const { //deep copy of this list (allocates links) if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); //call copy constructor of Link Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr)); next = next->getnext(); return head; List to copy (this instance of list): List - continued data_ next_ data_ next_ 0 head_ Copied List: data_ next_ 0 head
25 Link* List::copy() const { //deep copy of this list (allocates links) if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); //call copy constructor of Link Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr)); next = next->getnext(); return head; //origptr points to node in original list that is not yet copied List to copy (this instance of list): List - continued data_ next_ data_ next_ data_ next_ 0 gethead() Temp origptr Copied List: data_ next_ 0 head/next
26 Link* List::copy() const { //deep copy of this list (allocates links) if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); //call copy constructor of Link Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr));//create a new link for next next = next->getnext(); return head; //origptr points to node in original list that is not yet copied List to copy (this instance of list): List - continued data_ next_ data_ next_ data_ next_ 0 gethead() Temp origptr Copied List: data_ next_ data_ next_ 0 head/next next->setnext(...))
27 Link* List::copy() const { //deep copy of this list (allocates links) if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); //call copy constructor of Link Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr));//create a new link for next next = next->getnext(); return head; //origptr points to node in original list that is not yet copied List to copy (this instance of list): List - continued data_ next_ data_ next_ data_ next_ 0 gethead() Temp origptr Copied List: data_ next_ data_ next_ 0 head next
28 Link* List::copy() const { //deep copy of this list (allocates links) if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); //call copy constructor of Link Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr));//create a new link for next next = next->getnext(); return head; //origptr points to node in original list that is not yet copied List to copy (this instance of list): List - continued data_ next_ data_ next_ data_ next_ 0 gethead() Temp origptr Copied List: data_ next_ data_ next_ data_ next_ 0 head next
29 List - continued Link* List::copy() const { //deep copy of this list (allocates links) if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr)); next = next->getnext(); return head; List::List(const List &alist){ //Copy Constructor:deep copy of alist head_ = alist.copy(); List & List::operator=(const List &L) { //Assignment Operator if (this == &L) { //check for "self assignment" and do nothing in that case return *this; clear(); head_ = L.copy(); return *this;
30 Destructor An object's destructor function is called when that object is about to "go away. - A class instance (a value parameter or a local variable) goes out of scope - The dynamically allocated storage pointed to by the pointer is freed by the programmer using the delete operator
31 Destructor void f(list L) { //what is the scope of L? List *p = new List(); //what is the scope of P? while (...) { List L1; //what is the scope of L1?... delete p;
32 Destructor void f(list L) { //(object passed by value) copy constructor function was called List *p = new List(); //object's constructor function is called while (...) { List L1; //L1's constructor function is called... //L1's destructor function is called delete p; //object's destructor function is called //L's destructor function is called Is a destructor function of a reference parameter called at the end of the function?
33 // deceleration of detructor - always declared as virtual virtual ~List(); /** * Destructor: "deep delete" */ List::~List() { clear(); void List::removeFirst() { if (0!= head_) { Link* tmp = head_; head_ = head_->getnext(); delete tmp; void List::clear(){ while (0!= head_) { removefirst();
34 Copy Constructor An object's copy constructor is called (automatically, not by the programmer) when it is created, and needs to be initialized to be a copy of an existing object. This happens when an object is: - Passed as a value parameter to a function, for example: Point q(2,2); Point p(0,0); p.moveto(q); //declared as: moveto(point point) {... Returned (by value) as a function result, Declared with initialization from an existing object of the same class. void f(point p){ Point temp = p; Point temp2(p); //copy constructor called here to copy p //copy constructor called here to copy p
35 Example When copy constructors are being called? List f( List L ) { List tmp1 = L; List tmp2(l);... return tmp1; int main() { List L1, L2;... L2 = f( L1 );
36 Example List f( List L ) { List tmp1 = L; List tmp2(l);... return tmp1; // copy constructor called here to copy L // copy constructor called here to copy L // copy constructor called here // to copy tmp1 to L2 int main() { List L1, L2;... L2 = f( L1 ); // copy constructor called here to copy L1
37 Copy Constructor Declaration class List { public: List(const List &L); // copy constructor //L is the object that the copy constructor is supposed to copy... ; The copy constructor should copy - (sometimes called a deep copy): - the values of all non-pointer data members - the objects pointed to by all pointer data members
38 Copy Constructor Definition List::List(const List &alist){ head_ = alist.copy(); Link* List::copy() const { if (0 == gethead()) { return 0; else { Link *head = new Link(*getHead()); Link *next = head; for (Link *origptr = gethead()->getnext(); 0!= origptr; origptr = origptr->getnext()) { next->setnext(new Link(*origPtr)); next = next->getnext(); return head;
39 List L1, L2; Operator=... L1 = L2; // assignment can be written as: L1.operator=(L2) By default, class assignment is just a field-by-field assignment the above assignment is equivalent to: L1.data_ = L2.data_; L1.next_ = L2.next_; - If a class includes pointer fields, the default assignment operator causes aliasing which lead to trouble! Solution: overload operator= to perform deep copy. Syntax: List & operator=(const List &L);
40 =Operator Note that operator= differs from the copy constructor in 3 important ways: The object being assigned to has already been initialized. Therefore, if it has a pointer field, the storage pointed to, must be freed to prevent a storage leak. It is possible for a programmer to assign from a variable into itself. for example: L1 = L1. The operator= code must check for this case, and do nothing. The operator= code must return a value
41 Definition of operator= It should always include the following 4 sections: - check assignment to self - clear existing data members - copy data member from other - return this List & List::operator=(const List &L) { if (this == &L) { // check for "self assignment" and do nothing in that case return *this; clear(); head_ = L.copy(); return *this; // return this List
42 Objects In C++, object variables hold values, not object references. When one object is assigned to another, a copy of the actual values is made. When modifying an object in a function, you must remember to use call by reference. Two object variables cannot jointly access one object. If you need this effect in C++, then you need to use pointers/references. An object variable can only hold values of a particular type. If you want a variable to hold objects from different subclasses, you need to use pointers. If you want a variable point to either null or to an actual object, then you need to use pointers in C++.
43 The "this" Pointer Note that, as in Java, this is a pointer to the active object. So for example, when: L1 = L2 is executed, L1's member function operator= is called, so this is a pointer to L1. We also make use of this for the returned value in the operator=. the type to be returned is List& so we dereference this, a.k.a return *this. We would like to establish a way to distinguish between parameters and class variables. This can be done by the "this" pointer. It used as a pointer to the class object instance by the member functions. this pointer stores the address of the object instance, to enable pointer access of the object. this pointers are not accessible for static member functions. this pointers are not modifiable.
44 C++ STL examples - Vector void clean_odd(std::vector<int> &vec) { std::vector<int>::iterator iter = vec.begin(); while (iter!= vec.end()) { if (*iter % 2 == 0) { iter++; else { iter = vec.erase(iter); int main(int argc, char *argv[]) { std::vector<int> vec; vec.push_back(0); vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); Printout clean_odd(vec); for (std::vector<int>::iterator iter = vec.begin(); iter!= vec.end(); ++iter){ std::cout << *iter << std::endl; return 0;
45 C++ STL examples - Map int main(int argc, char *argv[]) { std::map<std::string,int> stringcounts; std::string str; std::vector<string> vec; vec.push_back("abc"); vec.push_back("123"); vec.push_back("qaz"); vec.push_back("789"); vec.push_back("abc"); vec.push_back("123"); Printout word: 123, count: 2 word: 789, count: 1 word: abc, count: 2 word: qaz, count: 1 std::vector<string>::iterator veciter = vec.begin(); while (veciter!= vec.end()) { std::map<std::string,int>::iterator found = stringcounts.find(*veciter); if (found!= stringcounts.end()) { found->second++; else { stringcounts.insert(std::make_pair(*veciter, 1)); veciter++; std::map<std::string,int>::iterator iter; for( iter = stringcounts.begin(); iter!= stringcounts.end(); ++iter) { std::cout << "word: " << iter->first << ", count: " << iter->second << std::endl; return 0;
46 C++ STL examples - Priority Queue class Cow { private: int _id; public: Cow(int id) : _id(id) { ; int getid() const { return _id; // A comparator is a class that implements the operator() // It is passed as a parameter to the priority queue // and used to perform the comparisons among items in the queue. class CowComparator { public: bool operator()(const Cow &x, const Cow &y) { // return true if x < y, false otherwise return x.getid() < y.getid(); ; int main(int argc, char *argv[]) { typedef std::priority_queue<cow, std::vector<cow>, CowComparator> PrioQueue; PrioQueue queue; queue.push(cow(0)); queue.push(cow(3)); queue.push(cow(1)); queue.push(cow(2)); Printout while (!queue.empty()) { std::cout << queue.top().getid() << std::endl; queue.pop();
Scope. Scope is such an important thing that we ll review what we know about scope now:
Scope Scope is such an important thing that we ll review what we know about scope now: Local (block) scope: A name declared within a block is accessible only within that block and blocks enclosed by it,
More informationC++ Constructor Insanity
C++ Constructor Insanity CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon
More informationCS 162 Intro to CS II. Structs vs. Classes
CS 162 Intro to CS II Structs vs. Classes 1 Odds and Ends Assignment 1 questions Why does the delete_info have a double pointer to states as a parameter? Do your functions have to be 15 or under? Anymore???
More informationCOMP 2355 Introduction to Systems Programming
COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract
More informationC++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!
C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a
More informationThe Class Construct Part 2
The Class Construct Part 2 Lecture 24 Sections 7.7-7.9 Robb T. Koether Hampden-Sydney College Mon, Oct 29, 2018 Robb T. Koether (Hampden-Sydney College) The Class Construct Part 2 Mon, Oct 29, 2018 1 /
More informationHomework 4. Any questions?
CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible
More informationC++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!
C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a
More informationPIC 10A. Lecture 15: User Defined Classes
PIC 10A Lecture 15: User Defined Classes Intro to classes We have already had some practice with classes. Employee Time Point Line Recall that a class is like a souped up variable that can store data,
More informationCSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 10 - references, const, classes Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New C++ exercise out today, due Friday morning
More informationCS11 Intro C++ Spring 2018 Lecture 1
CS11 Intro C++ Spring 2018 Lecture 1 Welcome to CS11 Intro C++! An introduction to the C++ programming language and tools Prerequisites: CS11 C track, or equivalent experience with a curly-brace language,
More informationPENN STATE UNIVERSITY Department of Economics
PENN STATE UNIVERSITY Department of Economics Econ 597D Sec 001 Computational Economics Gallant Sample Midterm Exam Questions Fall 2015 In class on Oct 20, 2015 1. Write a C++ program and a makefile to
More informationC++ and OO. l C++ classes and OO. l More Examples. l HW2. C++ for C Programmers by Ira Pohl
C++ and OO C++ classes and OO More Examples HW2 Objects C++ and OO What happens with a declaration int i, j = 3; Declares; allocates ; initializes For a simple native type this happens automatically via
More informationCS11 Intro C++ Spring 2018 Lecture 3
CS11 Intro C++ Spring 2018 Lecture 3 C++ File I/O We have already seen C++ stream I/O #include cout > name; cout
More informationDynamic Data Structures
Dynamic Data Structures We have seen that the STL containers vector, deque, list, set and map can grow and shrink dynamically. We now examine how some of these containers can be implemented in C++. To
More informationOutline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory
Outline 1 Chapter 10: C++ Dynamic Memory Proper Memory Management Classes which must allocate memory must manage it properly. Default behavior of operations in C++ are insufficient for this. The assignment
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationpointers & references
pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using
More informationFunction Templates. Consider the following function:
Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But
More information12/2/2009. The plan. References. References vs. pointers. Reference parameters. const and references. HW7 is out; new PM due date Finish last lecture
The plan 11/30 C++ intro 12/2 C++ intro 12/4 12/7 12/9 12/11 Final prep, evaluations 12/15 Final HW7 is out; new PM due date Finish last lecture David Notkin Autumn 2009 CSE303 Lecture 25 CSE303 Au09 2
More informationInformatik I (D-ITET) Übungsstunde 9, Hossein Shafagh
Informatik I (D-ITET) Übungsstunde 9, 20.11.2017 Hossein Shafagh shafagh@inf.ethz.ch Self-Assessment III 1) Characters: FILO - 2P for the completely correct answer - 0P otherwise 2) Pointers Self-Assessment
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College November 6, 2017 Outline Outline 1 Chapter 10: C++ Dynamic Memory Outline 1 Chapter 10: C++ Dynamic Memory Proper Memory Management
More informationLinked List using a Sentinel
Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include
More informationCS11 Introduction to C++ Fall Lecture 1
CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday
More informationCMSC 202 Final May 19, Name: UserID: (Circle your section) Section: 101 Tuesday 11: Thursday 11:30
CMSC 202 Final May 19, 2005 Name: UserID: (Circle your section) Section: 101 Tuesday 11:30 102 Thursday 11:30 Directions 103 Tuesday 12:30 104 Thursday 12:30 105 Tuesday 1:30 106 Thursday 1:30 This is
More informationThe Class Construct Part 1
The Class Construct Part 1 Lecture 23 Sections 7.5-7.6 Robb T. Koether Hampden-Sydney College Fri, Oct 26, 2018 Robb T. Koether (Hampden-Sydney College) The Class Construct Part 1 Fri, Oct 26, 2018 1 /
More informationAnnouncements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy
CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only
More informationWhere do we stand on inheritance?
In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public
More informationC:\Temp\Templates. Download This PDF From The Web Site
11 2 2 2 3 3 3 C:\Temp\Templates Download This PDF From The Web Site 4 5 Use This Main Program Copy-Paste Code From The Next Slide? Compile Program 6 Copy/Paste Main # include "Utilities.hpp" # include
More informationFinancial computing with C++
Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked
More informationCommon Misunderstandings from Exam 1 Material
Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself
More informationEECE.3220: Data Structures Spring 2017
EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday
More informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428
More informationAssignment of Objects
Copying Objects 1 Assignment of Objects 2 Slides 1. Table of Contents 2. Assignment of Objects 3. Dynamic Content 4. Shallow Copying 5. Deep Copying 6. this Pointer 7. Improved Deep Copy 8. Passing an
More informationFunction Declarations. Reference and Pointer Pitfalls. Overloaded Functions. Default Arguments
Reference and Pointer Pitfalls Function Declarations Never return a reference or a pointer to a local object. The return value will refer to memory that has been deallocated and will be reused on the next
More informationObject-Oriented Programming
Object-Oriented Programming Section 3: Classes and inheritance (1) Piotr Mielecki, Ph. D. piotr.mielecki@pwr.edu.pl pmielecki@gmail.com Class vs. structure declaration Inheritance and access specifiers
More information2 2
1 2 2 3 3 C:\Temp\Templates 4 5 Use This Main Program 6 # include "Utilities.hpp" # include "Student.hpp" Copy/Paste Main void MySwap (int Value1, int Value2); int main(int argc, char * argv[]) { int A
More informationHomework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 6 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 21, 2013 Question 1 What is the output of the following C++ program? #include #include using namespace
More informationLecture 15a Persistent Memory & Shared Pointers
Lecture 15a Persistent Memory & Shared Pointers Dec. 5 th, 2017 Jack Applin, Guest Lecturer 2017-12-04 CS253 Fall 2017 Jack Applin & Bruce Draper 1 Announcements PA9 is due today Recitation : extra help
More informationNamespaces and Class Hierarchies
and 1 2 3 MCS 360 Lecture 9 Introduction to Data Structures Jan Verschelde, 13 September 2010 and 1 2 3 Suppose we need to store a point: 1 data: integer coordinates; 2 functions: get values for the coordinates
More informationChapter 19 C++ Inheritance
Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes
More informationCSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning
More informationIntroducing C++ to Java Programmers
Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:
More informationeingebetteter Systeme
Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Tutorial (falk@cs.fau.de) 1 Agenda Classes Pointers and References Functions and Methods Function and Operator Overloading Template Classes
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example
More informationCOMP6771 Advanced C++ Programming
1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout
More informationCE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings
CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location
More informationPHY4321 Summary Notes
PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t
More informationLecture on pointers, references, and arrays and vectors
Lecture on pointers, references, and arrays and vectors pointers for example, check out: http://www.programiz.com/cpp-programming/pointers [the following text is an excerpt of this website] #include
More informationSoftware Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example
Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell
More informationModule 9. Templates & STL
Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions
More informationClasses - 2. Data Processing Course, I. Hrivnacova, IPN Orsay
Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member
More informationCMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am
CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103
More informationIntroduction to the C programming language
Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes
More informationThe University of Nottingham
The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, AUTUMN SEMESTER 2009-2010 C/C++ for Java Programmers Time allowed TWO hours Candidates may complete the front cover of their answer
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list
More informationAbstract Data Types (ADT) and C++ Classes
Abstract Data Types (ADT) and C++ Classes 1-15-2013 Abstract Data Types (ADT) & UML C++ Class definition & implementation constructors, accessors & modifiers overloading operators friend functions HW#1
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main
More informationECE 462 Midterm Exam 1. 10:30-11:20AM, September 21, 2007
ECE 462 Midterm Exam 1 10:30-11:20AM, September 21, 2007 1 Template Classes and the STL Library 1.1 Container Classes Which statement is correct? Answer: B A. An element can be inserted anywhere in a stack.
More informationChapter 19 - C++ Inheritance
Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions
More informationEL2310 Scientific Programming
Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes
More informationECE 462 Exam 1. 6:30-7:30PM, September 22, 2010
ECE 462 Exam 1 6:30-7:30PM, September 22, 2010 I will not receive nor provide aid to any other student for this exam. Signature: You must sign here. Otherwise, the exam is not graded. This exam is printed
More informationCS 11 C++ track: lecture 1
CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationSpring 2008 Data Structures (CS301) LAB
Spring 2008 Data Structures (CS301) LAB Objectives The objectives of this LAB are, o Enabling students to implement Singly Linked List practically using c++ and adding more functionality in it. o Enabling
More informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 13 -- smart pointers Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW2 is due on Thursday! - check out the discussion board for a few
More informationClass and Function Templates
Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationCSE 333 Final Exam December 13, 2017 Sample Solution
Question 1. (16 points) STL. Implement the template function is_sorted, below, so it returns true if its list argument is sorted in non-decreasing order, and returns false if not. Your function should
More informationMotivation for Templates
Motivation for You want both: a list of Location objects a list of MazeMonster objects 1 How can you accomplish this by writing one LinkedList class? state all the ways you can think of doing this state
More informationIntroduction to the C programming language
Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes
More informationMotivation for Templates. Class and Function Templates. One Way to Look at Templates...
Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates...
More informationCSCI-1200 Data Structures Spring 2018 Exam 1 Solutions
CSCI-1200 Data Structures Spring 2018 Exam 1 Solutions 1 Parcel Delivery [ / 35] In the following problem you will finish the implementation of a program that is designed to keep track of several delivery
More information2015 Academic Challenge
2015 Academic Challenge COMPUTER SCIENCE TEST - STATE This Test Consists of 30 Questions Computer Science Test Production Team James D. Feher, McKendree University Author/Team Leader Nathan White, McKendree
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationLecture 2, September 4
Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More informationFunctions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function
Functions in C++ Functions For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Declarations vs Definitions Inline Functions Class Member functions Overloaded
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationCS427 Inheritance and Virtual Functions. Linked lists. 2/27. 01Replacement.cpp link! i n t GetY ( void ) { return ( y ) ; } ;
Inheritance and Virtual Functions. Linked lists. CS427 Lecture 12.2, 11am, 26th March 2012 In today s class 1 Recall... Inheritance 2 3 4 Limitations of arrays 5 Linked lists 6 7 8 Further linked list
More informationLecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology
Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes
More informationPOLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE
Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public
More informationPOLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors
POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual
More informationCMSC 202 Midterm Exam 1 Fall 2015
1. (15 points) There are six logic or syntax errors in the following program; find five of them. Circle each of the five errors you find and write the line number and correction in the space provided below.
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationHomework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 5 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 13, 2013 Question 1 Consider the following Java definition of a mutable string class. class MutableString private char[] chars
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object
More informationCS31 Discussion. Jie(Jay) Wang Week8 Nov.18
CS31 Discussion Jie(Jay) Wang Week8 Nov.18 Outline Pointer Struct Memory Management When the program gets executed, it gets some amount of memory allocated for use. memory Program 1 Program 2 Memory Management
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationPraktikum: Entwicklung interaktiver eingebetteter Systeme
Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Labs (falk@cs.fau.de) 1 Agenda Writing a Vector Class Constructor, References, Overloading Templates, Virtual Functions Standard Template Library
More informationThe University of Nottingham
The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, SPRING SEMESTER 2011-2012 G52CPP C++ Programming Examination Time allowed TWO hours Candidates may complete the front cover of
More informationUniversity of Illinois at Urbana-Champaign Department of Computer Science. First Examination
University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section
More informationA506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).
A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary
More informationGCC : From 2.95 to 3.2
GCC : From 2.95 to 3.2 Topics Simple changes name of standard include files, std::endl, iostream, throw statements, vector iterators More complicated changes string streams, parameterized macros, hash_map
More informationCh 2 ADTs and C++ Classes
Ch 2 ADTs and C++ Classes Object Oriented Programming & Design Constructing Objects Hiding the Implementation Objects as Arguments and Return Values Operator Overloading 1 Object-Oriented Programming &
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More information