CS11 Introduction to C++ Fall Lecture 1

Similar documents
CS11 Intro C++ Spring 2018 Lecture 1

CS 11 C++ track: lecture 1

CS11 Introduction to C++ Fall Lecture 6

CS11 Intro C++ Spring 2018 Lecture 3

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CS11 Introduction to C++ Fall Lecture 3

Fast Introduction to Object Oriented Programming and C++

CSE 303: Concepts and Tools for Software Development

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

EL2310 Scientific Programming

CS3157: Advanced Programming. Outline

EL2310 Scientific Programming

Introduction to C++ Introduction to C++ 1

AN OVERVIEW OF C++ 1

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

EL2310 Scientific Programming

CS

C++ basics Getting started with, and Data Types.

CS11 Introduction to C++ Fall Lecture 2

CS24 Week 3 Lecture 1

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

A brief introduction to C++

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Constructor Insanity

Cpt S 122 Data Structures. Introduction to C++ Part II

Scientific Computing

Absolute C++ Walter Savitch

Short Notes of CS201

Lecture 14: more class, C++ streams

Object-Oriented Programming

CS201 - Introduction to Programming Glossary By

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

COMP322 - Introduction to C++ Lecture 01 - Introduction

CS11 Introduction to C++ Fall Lecture 7

Interview Questions of C++

Scope. Scope is such an important thing that we ll review what we know about scope now:

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CS11 Advanced C++ Fall Lecture 3

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

PIC 10A Objects/Classes

Computer Science II Lecture 1 Introduction and Background

Introduction to C++ Systems Programming

Computer Programming : C++

Computer Programming C++ Classes and Objects 6 th Lecture

CE221 Programming in C++ Part 1 Introduction

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:

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Engineering Tools III: OOP in C++

CS102 C++ Exception Handling & Namespaces

Operator overloading

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:

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Chapter 2 Basic Elements of C++

Ch 2 ADTs and C++ Classes

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

Chapter 2: Basic Elements of C++

Introducing C++ to Java Programmers

Introduction to C++ (Extensions to C)

Chapter 15 - C++ As A "Better C"

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

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Introduction to Programming using C++

EL2310 Scientific Programming

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

How to engineer a class to separate its interface from its implementation and encourage reuse.

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 28 OOPS IN C++ MICHAEL GROSSBERG

COEN244: Class & function templates

CS11 Java. Fall Lecture 1

Tutorial-2a: First steps with C++ programming

Programming with C++ as a Second Language

CIS 130 Exam #2 Review Suggestions

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Getting started with C++ (Part 2)

UEE1302 (1102) F10: Introduction to Computers and Programming

Abstract Data Types (ADT) and C++ Classes

Dr. Md. Humayun Kabir CSE Department, BUET

Chapter 1 Introduction to Computers and C++ Programming

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

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Cours de C++ Introduction

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

C++ For Science and Engineering Lecture 2

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

PHY4321 Summary Notes

Program Organization and Comments

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

CSE 333 Lecture 9 - intro to C++

An Introduction to C++

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

The Class Construct Part 2

CS 162 Intro to CS II. Structs vs. Classes

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

How to approach a computational problem

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

CS 376b Computer Vision

Transcription:

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 night Due one week later, on Monday at noon CS Cluster Account Development tools Electronic submission ~/cs11/cpp/lab1 etc.

CS11 C++ Track: Goals Proficiency with the C++ language Very complex language many subtleties Only a basic introduction to the Standard Library Good C++ idioms and ones to avoid Good software engineering practices How to write code that s easy to understand Techniques that help expose bugs Code that is easy to maintain and extend

Assignments and Grading Labs focus on lecture topics and lectures cover tricky points in labs Each lab will get a pass/fix, and feedback. If your code is broken, you will have to fix it. If your code is messy, you will have to clean it up. Must pass every assignment to pass CS11 Please turn in assignments on time No textbook is required Slides are posted on CS11 website

Tips and Tricks Books Many great books! Effective C++, More Effective C++ Scott Myers Exceptional C++, More Exceptional C++ Herb Sutter Exceptional C++ Style Herb Sutter These books teach you how to use C++ well Not necessary for this track A great investment if you use C++ a lot

C++ Origins Original designer: Bjarne Stroustrup AT&T Bell Labs First versions called C with Classes 1979 Most language concepts taken from C Class system conceptually derived from Simula67 Name changed to C++ in 1983 Continuous evolution of language features Many enhancements to class system; operator overloads; references; const; templates; exceptions; namespaces;

C++ Philosophy Close to the problem to be solved Ability to build elegant and powerful abstractions Strong focus on modularity Big enhancements to C type-system Close to the machine Retains C s focus on performance Also retains C s ability to do low-level manipulation of hardware and data

Two Components of C++ The C++ core language Syntax, data-types, variables, flow-control, Functions, classes, templates, The C++ Standard Library A collection of useful classes and functions written in the core language Generic strings, streams, exceptions Generic containers and algorithms The Standard Template Library (STL)

My First C++ Program Hello, World! #include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; return 0; } main() function is program s entry-point

Make It Go. Save your program in hello.cc Typical C++ extensions are.cc,.cpp,.cxx Compile your C++ program > g++ -Wall hello.cc -o hello > hello Hello, world! > We are using GNU C++ compiler, g++ Many other C++ compilers too

Console IO in C++ C uses printf(), scanf(), etc. Defined in the C header stdio.h #include <stdio.h> C++ introduces Stream IO Defined in the C++ header iostream #include <iostream> cin console input, from stdin cout console output, to stdout Also cerr, which is stderr, for error-reporting.

Stream Output The << operator is overloaded for stream-output Compiler figures out when you mean shift-left and when you mean output to stream Supports all primitive types and some standard classes endl means end of line in C++ Example: string name = "series"; int n = 15; double sum = 35.2; cout << "name = " << name << endl << "n = " << n << endl << "sum = " << sum << endl;

Stream Input The >> operator is overloaded for stream-input Also supports primitive types and strings. Example: float x, y; cout << "Enter x and y coordinates: "; cin >> x >> y; Input values are whitespace-delimited. Enter x and y coordinates: 3.2-5.6 Enter x and y coordinates: 4 35

C++ Stream IO Tips Don t use printf() and scanf() in C++. At least, not in this class. Don t mix C-style IO and C++ stream-io. They use the same underlying OS-resources! Can use endl to end lines, or "\n". These are actually not the same in C++ Use endl in this class.

C++ Namespaces Namespaces are used to group related items string, cin, cout part of C++ Standard Library All Standard Library code is in the std namespace Either write namespace::name everywhere std::cout << "Hello, world!" << std::endl; Or, declare that you are using the namespace! using namespace std;... cout << "Hello, world!" << endl; namespace::name form is called a qualified name

Classes and Objects Objects are a tight pairing of two things: State a collection of related data-values Behavior code that acts on those data-values in coherent ways Objects = Data + Code A class is a blueprint for objects The class defines the state and behavior of objects of that class Actually defines a new type in the language

C++ Terminology: Members A class is made up of members Data-members are variables associated with the class They store the class state Also called member variables or fields Member functions are operations that the class can perform The set of member functions specifies a class behavior The actual code for a member function is its implementation These functions generally (but not always) involve the class data-members as well

Instantiating Classes Can have many objects of a particular class Each object has its own separate data-members Calling member functions on one object doesn t affect other objects An object is an instance of a class The terms object and instance are equivalent A class is not an object

Member-Function Terminology Constructors initialize new instances of a class Can take arguments, but not required. No return-value. Every class has at least one constructor No-argument constructor is called the default constructor Destructors clean up an instance of a class This is where an instance s resources are released No arguments, no return-value Every class has exactly one destructor

Member Function Terminology Accessors allow internal state to be retrieved Provide control over when and how data is exposed Mutators allow internal state to be modified Provide control over when and how changes can be made Example: a vehicle class Internal state is a direction vector Mutators might be turnright() and turnleft()

Who Uses A Class? The designer or developer of the class Decides how to implement the class Also decides what functionality the class exposes, and what the class ought to hide. The user or client of the class Doesn t care so much about its implementation. Just wants to use it to do some work! Sometimes these are the same person, but often this is not the case!

Encapsulation and Abstraction Key OOP Concepts Hide implementation details from users They don t care about these details! Let them concentrate on what they are doing. State changes are controlled User can t directly change state Member functions can ensure valid state changes. Implementation details can change Functionality can be enhanced. Internal representation can be changed. as long as the external behavior stays the same!

Access Modifiers The class declaration states what is exposed and what is hidden. Three access-modifiers in C++ public Anybody can access it private Only the class itself can access it protected We ll get to this later Default access-level for classes is private. In general, other code can only access the public parts of your classes.

Classes Declarations and Definitions C++ makes a distinction between the declaration of a class, and its definition. The declaration describes the member variables and functions, and the access constraints. This is put in the header file, e.g. Point.hh The definition specifies the behavior the actual code of the member functions. This is put in a corresponding.cc file, e.g. Point.cc Users of our class include the declarations #include "Point.hh"

Point Class Declaration Point.hh // A 2D point class! class Point { double x_coord, y_coord; // Data-members public: Point(); Point(double x, double y); ~Point(); double getx(); double gety(); void setx(double x); void sety(double y); }; // Constructors // Destructor // Accessors // Mutators

Defining the Point s Behavior Point.cc #include "Point.hh" // Default (aka no-argument) constructor Point::Point() { x_coord = 0; y_coord = 0; } // Two-argument constructor - sets point to (x, y) Point::Point(double x, double y) { x_coord = x; y_coord = y; } // Cleans up a Point instance. Point::~Point() { // no dynamic resources, so doesn't do anything }

Defining the Point s Behavior (continued) // Returns X-coordinate of a Point double Point::getX() { return x_coord; } // Returns Y-coordinate of a Point double Point::getY() { return y_coord; } // Sets X-coordinate of a Point void Point::setX(double x) { x_coord = x; } // Sets Y-coordinate of a Point void Point::setY(double y) { y_coord = y; }

Using Our Point Now we have a new type to use! #include "Point.hh"... Point p1; Point p2(3, 5); // Calls default constructor // Calls 2-arg constructor cout << "P2 = (" << p2.getx() << "," << p2.gety() << ")" << endl; p1.setx(210); p1.sety(154); Point s guts are hidden. p1.x_coord = 452; // Compiler reports an error. Don t use parentheses with default constructor!!! Point p1(); // This declares a function!

What About The Destructor? In the Point class, destructor doesn t do anything! Point doesn t dynamically allocate any resources Compiler can clean up static resources by itself // Cleans up a Point instance. Point::~Point() { // no dynamic resources, so doesn't do anything } In this case, you could even leave the destructor out Compiler will generate one for you Always provide a destructor if your class dynamically allocates any resources!

C++ Function Arguments Function-arguments in C++ are passed by-value A copy of each argument is made The function works with the copy, not the original Example: void outputpoint(point p) { cout << "(" << p.getx() << "," << p.gety() << ")"; }... Point loc(35,-117); outputpoint(loc); // loc is copied Copying lots of objects gets expensive!

C++ References C++ introduces references A reference is like an alias for a variable Using the reference is like using what it refers to Really simple example: int i = 5; int &ref = i; ref++; cout << "Now i = " << i << endl; // Prints 6 ref is of type int & - reference to an int Using ref is identical to using i here

C++ References (2) More characteristics of references The referent can be changed just like a pointer Cleaner syntax just like a normal variable Can refer to primitive variables or objects float &f is a reference to a float primitive Point &p is a reference to a Point object Use object-references as function-arguments The object itself isn t copied, so it s much faster! Don t use references for primitive types (usually)

C++ References Are Constrained C++ references must refer to something. Nice for functions that require an object Example: a function to rotate a point by 90 Pointer way: void rotate90(point *p) What if NULL is passed for p?? (Actually, C++ uses 0 instead of NULL.) Reference way: void rotate90(point &p) Not possible to pass in nothing!

References Allow Side-Effects If you want side-effects, you can use references. void rotate90(point &p) { }... double x = p.getx(); double y = p.gety(); p.setx(y); p.sety(-x); Point f(5, 2); rotate90(f); f is changed by rotate90(). If you just want efficient function calls, beware of accidental side-effects!

The Importance of Good Style Complicated problems expose the importance of good coding style It s about understanding things easily Make peripheral issues easy to spot and fix Concentrate on the important issues! Most time spent debugging and maintaining existing code! maybe by you, after you ve forgotten the details most often by your coworkers Don t give them reasons to hate you.

Commenting Tips Don t repeat the code explain its purpose. BAD: i++; // Increment i. Don t overcomment; don t undercomment. Comments should be clear and concise Comment every function s purpose, at least briefly. Also comment every class purpose, and note any relevant implementation details.

Good Style Tips Don t want to spend time on syntax issues Mismatched or missing curly-braces { } Where a function or block begins or ends What s the scope of this variable?? Good naming also facilitates understanding Choose names that convey the semantic meaning A few exceptions to this rule: i, j, k are common loop-variable names Names should be only as long as necessary

Indentation and Brace-Placement One common style: int somefunc(int x, bool flag) { } if (flag) { } return x * 2; else { } return x * x; Consistent indentation scheme Indentation should be 2, 3, or 4 spaces Another common style: int somefunc(int x, bool flag) { if (flag) { return x * 2; } else { return x * x; } }

Using Spaces Put spaces around binary operators // Calculate discriminant of quadratic equation. double discriminant = b * b 4 * a * c; Put spaces after if, else, for, while, do keywords if (x < 6) { } for (j = 0; j < 23; j++) { } a[j] = x * j; Put spaces after commas result = somefunction(x, y, r, theta, value);

Coding Style Bad coding style will impact your productivity. It will take you more time to find syntax issues. Bad coding style will impact your peers. Best to get in the habit now!

This Week s Homework Create a simple 3D point class in C++. Use your class in a simple math program. Use console IO to drive your program. Learn how to compile and run your program. Test your program to make sure it s correct.

Next Time! More details about classes in C++ (hold on to your hats ) C++ dynamic memory allocation Destructors will quickly become very useful Assertions Have your code tell you when there are bugs.