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

Slides:



Advertisements
Similar presentations
Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
Advertisements

Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
CSE 374 Programming Concepts & Tools Hal Perkins Winter 2012 Lecture 19 – Introduction to C++
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
1 CSE 303 Lecture 21 Classes and Objects in C++ slides created by Marty Stepp
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CS-2303 System Programming Concepts
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
IT PUTS THE ++ IN C++ Object Oriented Programming.
Introduction to C++. Overview C++? What are references Object orientation Classes Access specifiers Constructor/destructor Interface-implementation separation.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Intro to C++ And Some Tools Opening Discussion zHave any questions come up since last class? Have you had a chance to look over the project.
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Object Oriented Programming Elhanan Borenstein copyrights © Elhanan Borenstein.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Hank Childs, University of Oregon May 13th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / / __.
C++ Memory Overview 4 major memory segments Key differences from Java
Object-Oriented Programming in C++
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Monday, Feb 3, 2003Kate Gregory with material from Deitel and Deitel Week 5 Lab 1 comments Hand in Lab 2 Questions from Last Week Classes continued Lab.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account sysadmin/account_request.cgi Need to know UNIX (Linux)
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 12 – C: structs, linked lists, and casts.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
1 Introduction to Object Oriented Programming Chapter 10.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Object-Oriented Programming (OOP) and C++
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
CSE 374 Programming Concepts & Tools
Hank Childs, University of Oregon
Overview 4 major memory segments Key differences from Java stack
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
Overview 4 major memory segments Key differences from Java stack
Brought to you by C++ Tutorial Brought to you by
Classes, Constructors, etc., in C++
CSE 303 Concepts and Tools for Software Development
SPL – PS3 C++ Classes.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

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

C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many more little conveniences (I/O, new/delete, function overloading, pass-by-reference, bigger standard library) Namespaces (kind of like Java packages) Stuff we won’t do: const, different kinds of casts, exceptions, templates, multiple inheritance, … We will focus on a couple themes rather than just a “big bag of new features to memorize” … 2

Our focus Object-oriented programming in a C-like language may help you understand C and Java better? We can put objects on the stack or the heap; an object is not a pointer to an object Still have to manage memory manually Still lots of ways to HCBWKMSCOD* Still distinguish header files from implementation files Allocation and initialization still separate concepts, but easier to “construct” and “destruct” Programmer has more control on how method-calls work (different defaults from Java) *hopefully crash, but who knows – might silently corrupt other data 3

References Lectures and sample code will have enough to get by for cse374 Beyond that, best place to start: C++ Primer, Lippman, Lajoie, Moo, 5 th ed., Addison-Wesley, 2013 Every serious C++ programmer should also read: Effective C++, Meyers, 3 rd ed., Addison-Wesley, 2005 Effective Modern C++, Meyers, O’Reilly, 2014 Additional “best practices” for C++11/C++14 Good online source: cplusplus.com 4

Hello World #include int main() { // Use standard output stream cout // and operator << to send "Hello World” // and a newline (end line) to stdout std::cout << "Hello World" << std::endl; return 0; } Differences from C: “new-style” headers (no.h), namespace access (::), I/O via stream operators, … Differences from Java: not everything is in a class, any code can go in any file, … –Can write procedural programs if that’s what you want 5

Compiling Need a different compiler than for C; use g++ on Linux. Example: g++ -Wall -g -std=c++11 -o hello hello.cc The.cc extension is a convention (just like.c for C), but less universal (also common:.cpp,.cxx,.C, …) Uses the C preprocessor (no change there) Now: A few “niceties” before our real focus (classes and objects) 6

I/O Operator << takes a “ostream” and (various things) and outputs it; returns the stream, which is why this works: std::cout << 3 << "hi" << f(x) << ’\n’; –Easier and safer than printf (type safe) Operator >> takes “istream” and (various things) and inputs into it –Easier and safer than scanf. Do not use pointers – int x; std::cin >> x; 7

>> and << Can “think of” >> and << as keywords, but they are not: –Operator overloading redefines them for different pairs of types In C and core C++ they mean “left-shift” and “right-shift” (of bits); undefined for non-numeric types –Lack of address-of for input ( cin>>x ) done with call-by-reference (coming soon) 8

Namespaces In C, all non-static functions in the program need different names –Even operating systems with tens of millions of lines Namespaces (cf. Java packages) let you group top-level names: namespace thespace {... definitions... } –Of course, then different namespaces can have the same function names and they are totally different functions –Can nest them –Can reuse the same namespace in multiple places Particularly common: in the.h and the.cc Example, the whole C++ standard library is in namespace std To use a function/variable/etc. in another namespace, do thespace::some_fun() (not. like in Java) 9

Using To avoid having to always write namespaces and :: use a using declaration Example: #include using namespace std; int main() { cout << "Hello World" << endl; return 0; } 10

Onto Classes and Objects Like Java: Fields vs. methods, static vs. instance, constructors Method overloading (functions, operators, and constructors too) Not quite like Java: access-modifier (e.g., private) syntax and default declaration separate from implementation (like C) funny constructor syntax, default parameters (e.g.,... = 0) Nothing like Java: Objects vs. pointers to objects Destructors and copy-constructors virtual vs. non-virtual (to be discussed) 11

Stack vs. heap Java: cannot stack-allocate an object (only a pointer to one; all objects are dynamically allocated on the heap) C: can stack-allocate a struct, then initialize it C++: stack-allocate and call a constructor (where this is the object’s address, as always, except this is a pointer) Thing t(10000); Java: new Thing(...) calls constructor, returns heap- allocated pointer C: Use malloc and then initialized, must free exactly once later, untyped pointers C++: Like Java, new Thing(…), but can also do new int(42). Like C must deallocate, but must use delete instead of free. (never mix malloc/free with new/delete!) 12

Destructors An object’s destructor is called just before the space for it is reclaimed A common use: Reclaim space for heap-allocated things pointed to (first calling their destructors) –But not if there are other pointers to it (aliases)?! Meaning of delete x : call the destructor of pointed- to heap object, then reclaim space Destructors also get called for stack-objects (when they leave scope) Advice: Always make destructors virtual (learn why soon) 13

Arrays Create a heap-allocated array of objects: new A[10]; Calls default (zero-argument) constructor for each element Convenient if there’s a good default initialization Create a heap-allocated array of pointers to objects: new A*[10]; More like Java (but not initialized?) As in C, new A() and new A[10] have type A* new A* and new A*[10] both have type A** Unlike C, to delete a non-array, you must write delete e Unlike C, to delete an array, you must write delete [] e Else HYCSBWK – delete must be told when it is deleting an array (otherwise it tries to delete a single element) 14

Digression: Call-by-reference In C, we know function arguments are copies –But copying a pointer means you still point to the same (uncopied) thing Same also works in C++; but can also use a “reference parameter” ( & character before var name) Function definition: void f(int& x) {x = x+1;} Caller writes: f(y) But it’s as though the caller wrote f(&y) and every occurrence of x in the function really said *x. So that little & has a big meaning. 15

Copy Constructors In C, we know x=y or f(y) copies y (if a struct, then member-wise copy) Same in C++, unless a copy-constructor is defined, then do whatever the copy-constructor says A copy-constructor by definition takes a reference parameter (else we’d need to copy, but that’s what we’re defining) of the same type Copy constructor vs. assignment –Copy constructor initializes a new bag of bits (new variable or parameter) –Assignment (=) replaces an existing value with a new one – may need to clean up old state (free heap data?) 16

const const can appear in many places in C++ code –Basically means “doesn’t change” or “won’t change”, but there are subtleties Examples: const int default_length = 125; // don’t use #define void examine (const thing &t); // won’t change t int getX() const; // won’t change *this “const correctness” is important in real C++ code –Learn it if you do any non-trivial C++ 17

Still to come So far we have classes and objects (class instances) –Enough for many interesting types, particularly small concrete types like strings, complex, date, time, etc For full object-oriented programming we still need (and have) subclassing, inheritance, and related things –Many similarities with Java, but more options and different defaults 18