CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++



Similar documents
Comp151. Definitions & Declarations

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

An Incomplete C++ Primer. University of Wyoming MA 5310

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

C++ INTERVIEW QUESTIONS

CORBA Programming with TAOX11. The C++11 CORBA Implementation

The C Programming Language course syllabus associate level

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

5 Arrays and Pointers

13 Classes & Objects with Constructors/Destructors

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

C++FA 5.1 PRACTICE MID-TERM EXAM

Goals for This Lecture:

Answers to Review Questions Chapter 7

Computer Programming C++ Classes and Objects 15 th Lecture

Moving from CS 61A Scheme to CS 61B Java

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Basics of I/O Streams and File I/O

Member Functions of the istream Class

Chapter 5 Functions. Introducing Functions

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

C++ Crash Kurs. C++ Object-Oriented Programming

How to: Use Basic C++, Syntax and Operators

1 Abstract Data Types Information Hiding

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Object Oriented Software Design II

C++ Overloading, Constructors, Assignment operator

public static void main(string[] args) { System.out.println("hello, world"); } }

Passing 1D arrays to functions.

Moving from C++ to VBA

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

C++ program structure Variable Declarations

Informatica e Sistemi in Tempo Reale

Common Beginner C++ Programming Mistakes

Coding conventions and C++-style

Ada for the C++ or Java Developer

Visual Studio 2008 Express Editions

J a v a Quiz (Unit 3, Test 0 Practice)

if and if-else: Part 1

Ch 7-1. Object-Oriented Programming and Classes

Project 2: Bejeweled

Lecture 2 Notes: Flow of Control

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CSI33 Data Structures

Chapter 8 Selection 8-1

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

arrays C Programming Language - Arrays

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

Java Interview Questions and Answers

Functions and Parameter Passing

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Tutorial on C Language Programming

Stacks. Linear data structures

Class 16: Function Parameters and Polymorphism

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

C++FA 3.1 OPTIMIZING C++

C++ for Safety-Critical Systems. DI Günter Obiltschnig Applied Informatics Software Engineering GmbH

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Introduction to Data Structures

Introduction to Java

Syllabus OBJECT ORIENTED PROGRAMMING C++

Introduction to Python

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

URI and UUID. Identifying things on the Web.

Note: Syntactically, a ; is needed at the end of a struct definition.

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Semantic Analysis: Types and Type Checking

Chapter 9 Text Files User Defined Data Types User Defined Header Files

C Compiler Targeting the Java Virtual Machine

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Programming Languages CIS 443

Brent A. Perdue. July 15, 2009

Adapter, Bridge, and Façade

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Introduction to Objective-C. Kevin Cathey

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

William Paterson University Department of Computer Science. Microsoft Visual C++.NET Tutorial Spring 2006 Release 1.0

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Data Structures using OOP C++ Lecture 1

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Course notes Standard C++ programming

Lecture 22: C Programming 4 Embedded Systems

Visual Basic Programming. An Introduction

CS106A, Stanford Handout #38. Strings and Chars

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

The separation principle : a principle for programming language design

A brief introduction to C++ and Interfacing with Excel

Code Refactoring and Defects

Java from a C perspective. Plan

Appendix M: Introduction to Microsoft Visual C Express Edition

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Transcription:

CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++ Most people taking CS193D will already have some experience with C++. This handout is a quick refresher in case it s been a while. If you need more detail, read Chapter 1 of the book (also coincidentally titled A Crash Course in C++). An Annotated Hello World The following dead simple C++ program shows all of the components of a C++ program: // helloworld.cpp // C++ standard headers don't use ".h" /* main() in C++ takes argc (the number of arguments) and argv (an array of arguments) */ int main(int argc, char** argv) // "std" is the standard C++ namespace, like a Java package std::cout << "Hello, World!" << std::endl; Namespaces Namespaces, like packages in Java, address the problem of naming conflicts between different pieces of code. For example, you might be writing some code that has a function called foo(). One day, you decide to start using a third-party library, which also has a foo() function. The compiler has no way of knowing which version of foo() you are referring to within your code. Namespaces solve this problem by allowing you to define the context in which names are defined. To place code in a namespace, simply enclose it within a namespace block: // namespaces.h namespace mycode void foo(); 1

// namespaces.cpp namespace mycode void foo() std::cout << "foo() in the mycode namespace" << std::endl; To call the namespace-enabled version of foo(): mycode::foo(); // calls the "foo" function in the "mycode" namespace To avoid being explicit about the namespace with every call, use using: #include "namespaces.h" using namespace mycode; int main(int argc, char** argv) foo(); // implies mycode::foo(); Namespaces are a great example of the difference between a hacked together C++ program and a production quality program. The programs you write should be namespace-savvy. Preprocessor Directives Java programmers may not be familiar with the notion of a preprocessor. A preprocessor is like a compiler that runs over the code before the real compiler does its work. In C and C++, lines that begin with # contain commands for the preprocessor. In C, the preprocessor is often used to create faux constants and gross inlined functions known as macros. These preprocessor features are present in C++ but are rarely used. The main use of the preprocessor in C++ is the #include mechanism. Unlike Java, C and C++ functions are declared separately from their definitions. The declaration (which for C++ classes is confusingly referred to as a class definition) is usually placed in a file that ends in.h. Typically, C++ header files also make use of the preprocessor to make sure 2

that they are only included a single time. Each header defines a unique symbol and will skip its content if the symbol is already defined: // myheader.h #ifndef MYHEADER_H #define MYHEADER_H // content of the header goes here #endif // MYHEADER_H Worth noting: In C++, the standard language headers are included using angle brackets (< and >) and do not traditionally use ".h", as shown above with <iostream>. Why not? Well, all of the standard C headers are also available within C++. When using the C headers, you do include the.h. Variables, Types, Conditionals, Loops, etc. Most of the basic types and other constructs are similar between C, Java, and C++. For example, the following snippet of code works in all three languages: int result = invalue; for (int i = invalue - 1; i > 1; i--) result *= i; return result; Dynamically Created Arrays and Heap Memory Recall that standard arrays live on the stack and their size is determined at compile time: int* myarray[30]; To create an array whose size is determined at runtime, you declare it on the heap by allocating new memory: int* myarray = new int[arraysize]; Heap memory must be released manually by calling delete. When releasing memory that was allocated an array, you must use the bracket version of delete: 3

delete[] myarray; Heap memory is also used in C to achieve pass-by-reference. We will get into pointer mechanics later in the quarter. For now, we don't need to use pointers for pass-byreference because we have References A reference is basically a short-hand for a pointer without the messiness of dereferencing or the ambiguity of ownership. Java doesn't have an analogous concept because object arguments to Java methods are passed by reference automatically. Since Java has an object class for every corresponding basic type (e.g. Integer for int), there is always a simple way to achieve pass-by-reference. In C++, the & character is used to indicate that a variable is a reference. For now, we'll just focus on references as parameters to functions and methods. There are some subtleties we'll get into later. The first version of addone() below does not use a reference, so the variable that is passed in remains unchanged. The second version uses a reference, so the underlying variable is actually modified within the function. References can be used for basic types as well as more complex types, like classes. void addone(int i) i++; // has no real effect since this is a copy of the original void addone(int& i) i++; // actually changes the original variable Strings C++ programmers make use of both traditional C-style strings (arrays of characters with a null terminator) and the C++ string class. The string class works much like the Java String class, which is to say that it behaves like you would expect: #include <string> using namespace std; 4

int main(int argc, char** argv) string str1 = "Hello"; string str2 = "World"; string str3 = str1 + " " + str2; cout << "str1 is " << str1 << endl; cout << "str2 is " << str2 << endl; cout << "str3 is " << str3 << endl; if (str3 == "Hello World") cout << "str3 is what it should be" << endl; else cout << "hmmm... str3 isn't what it should be" << endl; Classes For people who don't have much experience with Object-Oriented Programming, we'll be talking more about classes in (no pun intended) an upcoming class. Until then, just think of classes as similar to C structs with associated functions. Here is the syntax for a class definition: // Calculator.h class Calculator public: Calculator(); ~Calculator(); // external code can call these methods // constructor // destructor int add(int num1, int num2); // method float divide(float numerator, float denominator); // method bool getallownegatives(); void setallownegatives(bool invalue); // method // method protected: // external code can't access these members bool fallownegatives; // data member 5

; // note the semicolon at the end! The functionality, or methods, of the classes are defined as shown: // Calculator.cpp #include "Calculator.h" Calculator::Calculator() fallownegatives = false; // initialize the data member Calculator::~Calculator() // nothing much to do in terms of cleanup int Calculator::add(int num1, int num2) if (!getallownegatives() && (num1 < 0 num2 < 0)) std::cout << "Illegal negative number passed to add()" << std::endl; return num1 + num2; float Calculator::divide(float numerator, float denominator) if (!getallownegatives() && (numerator < 0 denominator < 0)) std::cout << "Illegal negative number passed to divide()" << std::endl; return (numerator / denominator); bool Calculator::getAllowNegatives() 6

return fallownegatives; void Calculator::setAllowNegatives(bool invalue) fallownegatives = invalue; Finally, here's how other parts of the code use and interact with the class: // CalculatorTest.cpp #include Calculator.h using namespace std; int main(int argc, char** argv) Calculator mycalc; // stack-based Calculator mycalc.setallownegatives(true); int result = mycalc.add(2, 2); cout << According to the calculator, 2 + 2 = << result << endl; Calculator* mycalc2; // heap-based Calculator mycalc2 = new Calculator(); // allocate a new object mycalc2->setallownegatives(false); float result2 = mycalc2->divide(2.5, 0.5); cout << "According to the calculator, 2.5 / 0.5 = " << result2 << endl; If You Need More Review For most of you, this handout was probably just a refresher. However, if you're coming from a C background or you need a little more help in any of these areas, check out Chapter 1 of the book. It has the same sections with similar examples, but much more detail. 7