pointers & references

Size: px
Start display at page:

Download "pointers & references"

Transcription

1 pointers & references

2 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24

3 // point.h #ifndef POINT_H_ #define POINT_H_ #include <iostream> using namespace std; // Represents a 2D Point class Point { public: Point(int newx, int newy): x(newx), y(newy) {}; Point() : x(0), y(0) {}; int getx() const {return x;} int gety() const {return y;} bool operator<(const Point& other) const; bool operator==(const Point& other) const; friend ostream& operator<<(ostream& os, const Point& p); private: int x; int y; }; #endif

4 // point.cpp #include <iostream> #include "point.h" using namespace std; // p1 < p2 if (p1.x < p2.x )or ((p1.x equals p2.x) and p1.y < p2.y) bool Point::operator< (const Point& other) const { return (x < other.x) ((x == other.x) && (y < other.y)); } // p1 is "equal to" p2 iff (p1.x) equals (p2.x) and (p1.y) equals (p2.y) bool Point::operator== (const Point& other) const { return (x == other.x) && (y == other.y); } ostream& operator<< (ostream& os, const Point& p) { os << "[" << p.x << "," << p.y << "]" << endl; return os; }

5 Item 3:* Use const whenever possible We ve seen several examples of this in our member functions, such as ==, >>, etc. * Effective C++, 3 rd Edition, p. 17

6 Item 4:* Make sure that objects are initialized before they re used. example: suppose you have the following in C++ int x; question: does x have a random value or is it zero? answer: in some contexts, x is guaranteed to be initialized (to zero in this case), but in others it is not (e.g. local variables are not automatically initialized). solution: always initialize variables yourself * Effective C++, 3 rd Edition, p. 26

7 Item 4:* Make sure that objects are initialized before they re used. example: class Point { private: int x, y; } application program: int main() { } Point p; // calls default constructor return 0; The purpose of a constructor is to initialize all data members (instance variables). You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly.

8 implicit (code in class definition, e.g. Point) class Point { public: int getx() const { return x; } // }; explicit (code in implementation file, e.g. Time) inline void Time::read(istream& in) { in >> hours; in.get(); in >> minutes: }

9 An inline specifier for a function f is a suggestion to the compiler that it should attempt to replace each function call to f with the code body of f. FAQ what are some performance considerations with inline functions? 1. They might improve performance, or they might make it worse. 2. They might cause the size of the executable to increase, or they might make it smaller.

10 from Google C++ style guide It is important to know that functions are not always inlined even if they are declared as such Define functions inline only when they are small, say, 10 lines or less. Constructors, accessors & mutators and other short performance-critical functions are good candidates. Don t inline functions that contain loops or switch statements recursive functions be very careful before inlining a destructor

11 Declaring a reference variable is a way to give an object an alternative name. Example: double& rx = x; both x and rx refer to the same object. Note that rx itself is not an object it s a referent to another object. Consider the following assignment statement rx = 15; This changes x s value to 15; rx is unchanged (still a referent to x)

12 By default, functions are called by value. A copy of the arguments are made and stored into objects corresponding to the parameters. Any changes made to the parameter values do not affect the original argument objects. If a parameter is declared to be a reference type, then: The parameter is bound to the argument. Any change made to the parameter is made to the original argument.

13 Pass-by-Value: void swap (int x, int y) { int temp = x; x = y; y = temp; } int main() { x = 42 y = 24 int a = 42, b = 24; swap(a,b); cout << a << b << endl; } // prints Pass-by-Reference: void swap (int &x, int &y) { int temp = x; x = y; y = temp; } int main() { int &x = a int& y = b int a = 42, b = 24; swap(a,b); cout << a << b << endl; } // prints 24 42

14 Class types may occupy several storage locations in memory. Passing a class type object by value is inefficient. By declaring the parameter to be a const reference, function can access the value of the argument, but not change it.

15 // given a character c and a string s, counts and returns // the number of times c occurs in s (possibly zero) int count_occurences(char c, const string& s) { int count = 0; for (int i = 0; i < s.size(); i++) { if (c == s[i]) count++; } return count; }

16 More examples class Point { public: Point(int i, int j) : x(i), y(j) { } Point() : x(0), y(0) { } int getx() const { return x; } bool operator<(const Point& other) const; friend ostream& operator<<(ostream& os, const Point& p);

17 A pointer is a variable whose value is the memory address of an object (&obj) means the memory address of obj (*p) means the object that pointer p is currently pointing to int k = 25; // k s value is the integer 25 int *p = &k; // p s value is the memory address of k *p = -7 // changes k (p is unchanged) cout << k <<, << (*p) << endl;

18 Reference version: void swap (int &x, int &y) { int temp = x; x =y; y = temp; } int main() { int &x = a int& y = b int a = 42, b = 24; swap(a,b); cout << a << b << endl; } // prints Pointer version: void swap (int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { x = &a y = &b int a = 42, b = 24; swap(&a,&b); cout << a << b << endl; } // prints 24 42

19 NEVER dereference the NULL pointer! int *p; p = NULL; cout << *p; /* but p is not pointing to anything! */ *p = 42; /* ARRRRRRGGGGHHH! core dump */ if (p!= NULL) /* fail-safe programming */ cout << *p;

20 int x = 5; int *px = &x; int& rx = x; x and px are separate variables in memory; rx is not A reference must be assigned a value when it is declared; after that, it cannot be changed. A pointer can be changed. A pointer can point to NULL while reference cannot have the value NULL. You can't take the address of a reference like you can with pointers Pointer arithmetic is allowed (e.g. px = px + 2). There's no "reference arithmetic"

21 As a general rule, Use references in function parameters and return types to define attractive interfaces. Use pointers to implement algorithms and data structures.

22 For a type T, T[size] is the type array of size elements of type T ; elements are indexed from 0 to size-1 The number of elements (size) must be a constant expression Arrays can be initialized with an initialization list An array of objects is initialized by calling the default constructor for the object (unless an initialization list is provided). int c[3] = {127, 255, 212}; float temperature[7]; // might not be initialized Point triangle[3]; // calls Point::Point()

23 Arrays have a fixed, predetermined size Arrays don t know their size Arrays don t support the usual operators (assignment, ==, <, etc.) It is not easy to have a function return a copy of an array Recommendation: use container classes

24 FAQ 28.01: What are container classes? Answer: Containers are objects that hold other objects. Examples include vectors, lists, queues, and sets, among others. FAQ 2.15: What are the basics of using container classes? Answer: Templates are one of the most powerful code reuse mechanisms in C++. The most common use for templates is for containers. e.g. vector<t>, list<t>, set<t>

25 An enhancement of the array. Can be used like an array: access a value with an index, e.g. x = v[i]; v[j] = z; The size of a vector is not constant it can grow or shrink A vector knows its current size Additional capabilities: Insert an element at a specified position Remove an element from a specified position Overloads the assignment operator (=) and comparisons: <, <=, ==, >, >=,!=, etc. Functions can return a vector

26 The C++ standard library contains standard template classes (known as the Standard Template Library, or STL). Some methods include: constructor copy constructor destructor assignment op= size() push_back() cf. Table 5.1, Maciel

27 general form: vector<t> where T is a type vector<double> stats; // vector of doubles vector<float> v(10); // vector of 10 floats vector<string> file_contents;

28 vector<point> polygon; Point p1(100,200); Point p2(150,150); Point p3(150,50); Point p4(75,90); polygon.push_back(p1); polygon.push_back(p2); polygon.push_back(p3); polygon.push_back(p4); for (int i = 0; i < polygon.size(); i++) cout << polygon[i] << endl;

29 preface.txt After a few computer science courses, students may start to 2 get the feeling that programs can always be written to 3 solve any computational problem. Writing the program may 4 be hard work. For example, it may involve learning a 5 difficult technique. And many hours of debugging. But 6 with enough time and effort, the program can be written. 7 8 So it may come as a surprise that this is not the case: 9 there are computational problems for which no program next previous open quit command: o file: introduction.txt

30 void run_file_viewer() main function of the file viewer displays the given number of lines asks user what to do next: q o quit open a text file vector<string> v_document_lines data structure for storing the document s lines

31 void run_file_viewer() { vector<string> v_document_lines; string file_name; open_file(file_name, v_document_lines); while (true) { // while command is not 'quit' display(file_name, v_document_lines); cout << "command: "; char command = '-'; cin.get(command); cin.get(); // '\n' switch (command) { case 'q': return; case 'o': { open_file(file_name, v_document_lines); } // end case o } // end switch } // end while } // end run_file_viewer

32 void display(const string & file_name, const vector<string> & v_document_lines) { cout << endl << file_name << endl; string long_separator(50, '-'); cout << long_separator << endl; for (int i = 0; i < v_document_lines.size(); ++i) cout << setw(3) << i+1 << " " << v_document_lines[i] << endl; cout << long_separator << endl << " open quit" << endl; string short_separator(8, '-'); cout << short_separator << endl; } // end display

33 For Thursday, read Maciel, Chapter 5 Quiz #1 on Thursday, 1/24, in class

I/O streams

I/O streams I/O streams 1-24-2013 I/O streams file I/O end-of-file eof reading in strings Browse the following libraries at cplusplus.com String Library STL: Standard Template Library (vector) IOStream Library HW#2

More information

Abstract Data Types (ADT) and C++ Classes

Abstract 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 information

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Review: C++ Basic Concepts. Dr. Yingwu Zhu Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to

More information

CSE 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 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 information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

The Class Construct Part 2

The 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 information

COEN244: Class & function templates

COEN244: 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 information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Comp151. Generic Programming: Container Classes

Comp151. Generic Programming: Container Classes Comp151 Generic Programming: Container Classes Container Classes Container classes are a typical use for class templates, since we need container classes for objects of many different types, and the types

More information

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47 Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers

More information

pointers + memory double x; string a; int x; main overhead int y; main overhead

pointers + memory double x; string a; int x; main overhead int y; main overhead pointers + memory computer have memory to store data. every program gets a piece of it to use as we create and use more variables, more space is allocated to a program memory int x; double x; string a;

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

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: 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 information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

C++ Constructor Insanity

C++ 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 information

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008 COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008 Lab topic: 1) Take Quiz 4 2) Discussion on Assignment 2 Discussion on Assignment 2. Your task is to

More information

Copy Constructors & Destructors

Copy Constructors & Destructors Copy Constructors & Destructors 2-07-2013 Implementing a vector class local functions implicit constructors Destructors Copy Constructors Project #1: MiniMusicPlayer Quiz today 2/7/13 vectors and reading

More information

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes

More information

CS 247: Software Engineering Principles. ADT Design

CS 247: Software Engineering Principles. ADT Design CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data

More information

Ch 2 ADTs and C++ Classes

Ch 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 information

Use the dot operator to access a member of a specific object.

Use the dot operator to access a member of a specific object. Lab 16 Class A class is a data type that can contain several parts, which are called members. There are two types of members, data member and functions. An object is an instance of a class, and each object

More information

Introducing C++ to Java Programmers

Introducing 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 information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

Programming, numerics and optimization

Programming, 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 information

CS250 Final Review Questions

CS250 Final Review Questions CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure that you review all previous exams and make sure you fully understand

More information

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Homework 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 information

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

More information

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy CAAM 420 Fall 2012 Lecture 29 Duncan Eddy November 7, 2012 Table of Contents 1 Templating in C++ 3 1.1 Motivation.............................................. 3 1.2 Templating Functions........................................

More information

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University C++ Review CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose of Review Review some basic C++ Familiarize us with

More information

STL: C++ Standard Library

STL: C++ Standard Library STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

Topics. bool and string types input/output library functions comments memory allocation templates classes

Topics. bool and string types input/output library functions comments memory allocation templates classes C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers

More information

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures C++ Review 1 Purpose of Review Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures 2 Class The Class defines the data structure

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Exercise 6.2 A generic container class

Exercise 6.2 A generic container class Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input

More information

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers. CS 7A Final Exam - Fall 206 - Final Exam Solutions 2/3/6. Write the number of the definition on the right next to the term it defines. () Defining two functions or operators with the same name but different

More information

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++ 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 information

Engineering Tools III: OOP in C++

Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Why C++? C++ as a powerful and ubiquitous tool for programming of numerical simulations super-computers (and other number-crunchers)

More information

Object oriented programming

Object oriented programming Exercises 6 Version 1.0, 21 March, 2017 Table of Contents 1. Operators overloading....................................................... 1 1.1. Example 1..............................................................

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

CSE 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 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 information

1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks.

1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks. 1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks. Question 1. The following code is to be built and run as follows: Compile as Link as

More information

Unit IV Contents. ECS-039 Object Oriented Systems & C++

Unit IV Contents. ECS-039 Object Oriented Systems & C++ ECS-039 Object Oriented Systems & C++ Unit IV Contents 1 Principles or object oriented programming... 3 1.1 The Object-Oriented Approach... 3 1.2 Characteristics of Object-Oriented Languages... 3 2 C++

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

Lecture 3 ADT and C++ Classes (II)

Lecture 3 ADT and C++ Classes (II) CSC212 Data Structure - Section FG Lecture 3 ADT and C++ Classes (II) Instructor: Feng HU Department of Computer Science City College of New York @ Feng HU, 2016 1 Outline A Review of C++ Classes (Lecture

More information

Module 9. Templates & STL

Module 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 information

CS 211 Winter 2004 Sample Final Exam (Solutions)

CS 211 Winter 2004 Sample Final Exam (Solutions) CS 211 Winter 2004 Sample Final Exam (Solutions) Instructor: Brian Dennis, Assistant Professor TAs: Tom Lechner, Rachel Goldsborough, Bin Lin March 16, 2004 Your Name: There are 6 problems on this exam.

More information

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

Short Notes of CS201

Short 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 information

SFU CMPT Topic: Class Templates

SFU CMPT Topic: Class Templates SFU CMPT-212 2008-1 1 Topic: Class Templates SFU CMPT-212 2008-1 Topic: Class Templates Ján Maňuch E-mail: jmanuch@sfu.ca Monday 3 rd March, 2008 SFU CMPT-212 2008-1 2 Topic: Class Templates Class templates

More information

Implementing an ADT with a Class

Implementing an ADT with a Class Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More information

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++ 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 information

CSC1322 Object-Oriented Programming Concepts

CSC1322 Object-Oriented Programming Concepts CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.

More information

CS201 - Introduction to Programming Glossary By

CS201 - 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 information

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.

More information

1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks.

1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks. 1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks. Question 1. The following code is to be built and run as follows: Compile as Link as

More information

COMP322 - Introduction to C++ Lecture 01 - Introduction

COMP322 - Introduction to C++ Lecture 01 - Introduction COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in: CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also

More information

A506 / 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). 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 information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Practice Problems CS2620 Advanced Programming, Spring 2003

Practice Problems CS2620 Advanced Programming, Spring 2003 Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

1 Short Answer (5 Points Each)

1 Short Answer (5 Points Each) 1 Short Answer ( Points Each) 1. Find and correct the errors in the following segment of code. int x, *ptr = nullptr; *ptr = &x; int x, *ptr = nullptr; ptr = &x; 2. Find and correct the errors in the following

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

Namespaces and Class Hierarchies

Namespaces 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 information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

Dynamic Data Structures

Dynamic 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 information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor Operator overloading

More information

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 22, 2017 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

II. OPERATOR OVERLOADING

II. OPERATOR OVERLOADING II. OPERATOR OVERLOADING II.0 Preamble friend declaration Remember that private members can be accessed neither from member functions of other classes nor from independent functions. C++ gives the possibility

More information

Where do we stand on inheritance?

Where 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 information

CS11 Intro C++ Spring 2018 Lecture 1

CS11 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 information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information

CS 376b Computer Vision

CS 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 information

Operator Overloading

Operator Overloading Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions.... 2 2 I/O Operators 4 3 Comparison Operators 6 3.1 Equality Operators....... 11 3.2 Less-Than Operators...... 13 1 1 Operators

More information

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists

CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

Spare Matrix Formats, and The Standard Template Library

Spare Matrix Formats, and The Standard Template Library Annotated slides CS319: Scientific Computing (with C++) Spare Matrix Formats, and The Standard Template Library Week 10: 9am and 4pm, 20 March 2019 1 Sparse Matrices 2 3 Compressed Column Storage 4 (Not)

More information

Operator overloading: extra examples

Operator overloading: extra examples Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

Circle all of the following which would make sense as the function prototype.

Circle all of the following which would make sense as the function prototype. Student ID: Lab Section: This test is closed book, closed notes. Points for each question are shown inside [ ] brackets at the beginning of each question. You should assume that, for all quoted program

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

More information

Operators. The Arrow Operator. The sizeof Operator

Operators. The Arrow Operator. The sizeof Operator Operators The Arrow Operator Most C++ operators are identical to the corresponding Java operators: Arithmetic: * / % + - Relational: < = >!= Logical:! && Bitwise: & bitwise and; ^ bitwise exclusive

More information

การทดลองท 8_2 Editor Buffer Array Implementation

การทดลองท 8_2 Editor Buffer Array Implementation การทดลองท 8_2 Editor Buffer Array Implementation * File: buffer.h * -------------- * This file defines the interface for the EditorBuffer class. #ifndef _buffer_h #define _buffer_h * Class: EditorBuffer

More information

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information