Sixth lecture; classes, objects, reference operator.

Similar documents
These are notes for the third lecture; if statements and loops.

C++ for Java Programmers

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

CMSC202 Computer Science II for Majors

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

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

QUIZ. What is wrong with this code that uses default arguments?

Exercise: Inventing Language

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

C++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5

PIC 10A Objects/Classes

Dynamic Memory Allocation

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Operator overloading

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

a data type is Types

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Lesson 13 - Vectors Dynamic Data Storage

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

Chapter 1 Getting Started

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Exam 3 Chapters 7 & 9

Chapter 2 Basic Elements of C++

Pointers and References

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

C++ Support Classes (Data and Variables)

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

Program Organization and Comments

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

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

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

Practice test for midterm 2

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

Software Design and Analysis for Engineers

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Lab # 02. Basic Elements of C++ _ Part1

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Chapter 2: Basic Elements of C++

My First Command-Line Program

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Object-Oriented Programming, Iouliia Skliarova

Variables and Constants

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Copy Constructors & Destructors

CS 103 Lab - Party Like A Char Star

CS3157: Advanced Programming. Outline

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Basic Types and Formatted I/O

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

CS11 Advanced C++ Fall Lecture 7

CSCI Wednesdays: 1:25-2:15 Keller Thursdays: 4:00-4:50 Akerman 211

Announcements. Lab 1 this week! Homework posted Thursday -Due next Thursday at 11:55pm

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

Welcome to... CS113: Introduction to C

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Separate Compilation Model

Objectives. In this chapter, you will:

Computer Science II Lecture 1 Introduction and Background

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

primitive arrays v. vectors (1)

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Welcome to Lab! Feel free to get started until we start talking! The lab document is located on the course website:

Looping and Counting. Lecture 3. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

C++ Programming: From Problem Analysis to Program Design, Third Edition

CSI33 Data Structures

CSE 303: Concepts and Tools for Software Development

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

C++: Overview and Features

Programming in C++ PART 2

Chapter 18 Vectors and Arrays [and more on pointers (nmm) ] Bjarne Stroustrup

A brief introduction to C++

EEE145 Computer Programming

CS11 Advanced C++ Spring 2018 Lecture 2

CSCI-1200 Data Structures Fall 2012 Lecture 5 Pointers, Arrays, Pointer Arithmetic

Intro. Scheme Basics. scm> 5 5. scm>

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

Visual C# Instructor s Manual Table of Contents

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

UNIT- 3 Introduction to C++

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Ch. 11: References & the Copy-Constructor. - continued -

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

CS 32. Lecture 5: Templates

CSE : Python Programming

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Transcription:

Sixth lecture; classes, objects, reference operator. 1

Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours are 2-4pm Tuesdays and Thursdays, my office in 228 Hardymon feel free to stop by. The virtual desktop now has Tortoise installed by default, so you won t have to go through that step using it. But for the labs, you should be able to just use the tools (Visual Studio and Tortoise) installed on the lab machines themselves getting started with the virtual desktops was to make sure everyone was familiar with them and to give everyone base line functionality through them. You can continue using them if you want, but don t need to. 2

An email I received from a student this morning. I promise source control is useful. It s great. It s really helpful. It just has a bit of a learning curve, and hopefully we re past that but the bigger these projects get, the more useful it gets. It s a great habit to be in to write all of your code under source control and use it for frequent backups. 3

Dr. Jaromczyk asked me to relay information about the ACM programming competition; in 2010, the UK team went to the world finals in China. The local round is starting up this Thursday afternoon. http://www.cs.uky.edu/~jurek/ukspc/2012/index.sphp 4

Yeah, this is going to be the second (er, fifth?) slide in a lot of lectures. 5

Not the last time you ll se this. Why? Because it s important. 6

Parts of a function definition. 7

Debugger commands. Again, it will help you a lot to be familiar with these. 8

Going in to some of the stuff we discussed the mechanics of in the last class in more detail, to make sure we cover the concepts thoroughly. What is a variable? 9

So, we declare a variable. What does it do? This statement gives us a variable named a that we can access later (by the scope rules we ve discussed before). It assigns the value of 5 to it. It also allocates a memory location for a to store any value we assign to it. 10

The important concepts for passing variables to functions: Pass by value, pass by reference. It is very important to understand the difference between the two. 11

When we pass by value, C++ creates a new variable (and allocates new memory for it) within the function. 12

When we pass by reference, the same variable gets reused. This happens because the function, instead of just getting the value of the variable, gets passed its memory location, and can then access the memory that contains the original variable. 13

Syntax for passing by value type, variable name. Simple. C/C++ actually has pretty simple rules for pass by value/reference; if you see the reference declarator (&), it passes the value by reference, otherwise it passes by value. 14

Here we have the reference declarator (&); this passes the value by reference, so not only do we reuse the memory location, but this function can now modify the value stored in the variable. 15

And so it is often the case when we re passing by reference that we don t want the function to be able to do this, so we can use the const keyword here to prevent the function from changing the value of the variable. 16

We already talked about the reference declarator -- &. The ampersand character is also used as the reference operator. As we ve already discussed, C++ (and more so C, as this behavior comes directly from C) is a fairly old language, and derives from the days where character sets were more limited, and so they needed to reuse symbols in the language. So & can be used both as a declarator in a function parameter, but as an unary operator in a normal expression as well. When we use this in a normal expression, it returns the memory location of the attached variable. While we ll use it today to demonstrate that pass-by-reference semantics reuse memory locations and pass-by-value don t, this operator will become a lot more important when we talk about pointers soon But first 17

We ll talk a bit about classes and objects. We ve kinda skirted around this so far; we ve talked about strings and vectors (which are classes), but not a whole lot about how they differ from scalar types. A class is an abstract type; like string, vector, etc. In the same way as int, double, etc are types, string and vector are classes. An object is an instantiation of a class. When you declare a variable of a class such as string s; you get an object of that class. s is the object, string is the class. Classes have a lot of differences from the scalar types; one of the most notable is that while scalars do not have any default initialization, classes do string s; defaults to an empty string. Even without assignment, classes have default values. 18

This doesn t mean they can t be initialized however, as seen above. This slide also shows us calling a function length(), above within the class. We call these functions methods or member functions, and we ve used them a bit before, but now we ll talk about them more explicitly. 19

Another operator! This, the humble period, is the member operator (also called the structure reference operator). It s what we use to access the members within an object. Like the other operators, it takes part in expression evaluation (remember: everything is an expression), by finding the method within the object it s used on to call. We ve seen: string s = Hello, world! ; cout << s has << s.length() << characters. << endl; The period in s.length() is an example of the operator it lets us call the length method inside the object s. 20

Now some of the methods of the string class. We ve talked about declaring and initializing strings (and reading them in from the console, too), but now let s talk about some of the methods we can call on string objects. 21

size()/length() these are the same method, and both return the number of characters in the string. resize() resizes the string. The first argument is what size the string is being resized to, the second argument is the value to replace any added characters with. By default, it will use spaces. s.resize(3); // resizes the string to 3 characters; any additional characters are lost, if it adds characters, it will add spaces s.resize(10, * ); // resize the string to ten characters; if this causes characters to be added to the string, it will add asterisks. []/at() [] is the index operator. You put an integer value in it, and you get back the character at that index NOTE: strings are zero-indexed, which means the index of the first character is 0. at() is the same operation as a function. Causes an error if you ask for an index that doesn t exist in the string. char c1 = s[2]; // c is the third character in the string char c2 = s.at(2); // does the same thing as the above clear() resets the string to an empty string find() finds a character or string within the string, will return string::npos if it is not found; string::npos is equal to -1. 22

string s = Hello, world! ; if( s.find( * ) == -1 ) { cout << No asterisks. << endl; } int iindex = s.find( e ); // this will return 1, as e occurs at position 1 remember that strings start at position 0! + - we can add strings. This works pretty much how you d expect. Note: you can t add a literal string to another literal string, but you can add a literal string to a string object. string s = world ; string s2 = Hello, + s; // s2 is now Hello, world string s3 = Hello, + world ; // compiler error; you cannot add a literal string to a literal string 22

The other class we ve talked about vector. Vectors are a parameterized type; to declare one, we have to give it another type as a parameter: vector<int> will give us a vector of ints, vector<string> gives us a vector of strings. 23

Some methods in vector: size() returns the number of elements in the vector resize() resizes the vector to the given size. The optional second parameter tells it what default value to use if it has to add elements. vector<int> v; v.resize(10, 44); // Now v is a vector of ten ints, all with value 44. [] / at() works much like in string, which shouldn t be too surprising, as a string is, basically, a vector of characters with a few features added. int a = v[5]; // takes the sixth element in v remember vectors are zero indexed too int b = v.at(5); // does the same as above push_back() adds the parameter to the end of the vector pop_back() removes the element on the end of the vector v.resize(0); // v now has no elements v.push_back(3); v.push_back(4); // v now has two elements: 3 at position 0, 4 at position 1. v.pop_back(); // v now has one element: 3 at position 0. 24

We ve talked a lot about implicit casts, especially how they work with bool values, as that matters a lot for conditional statements. We re going to talk briefly about explicit casts, now when you specifically want an expression to be a different value than what it is by default 25

This is the general syntax for it when we re talking about scalar values we ll talk about casting objects later, but for scalars, this is how to do it. And, like vectors, this is parameterized the type you put in the angled braces is the type C++ will try to give you. The expression can be anything, well, because everything is an expression Example: string s = ABC ; cout << s.at(0) << endl; // This will write A to the console; the return type of string::at() is char, and cout writes chars to the console as letters int a = s.at(0); // A now holds the value 65; a char (the normal type of string::at()) can be implicitly converted to an int cout << a << endl; // This will write 65 to the console, as a is an int, and ints get written to the console as decimal numbers cout << static_cast<char>(a) << endl; // This will write A to the console, as chars get written out as letter, and the static_cast convers a to a char 26