From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Similar documents
CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

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

CS3157: Advanced Programming. Outline

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

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

Instantiation of Template class

Separate Compilation Model

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Short Notes of CS201

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

Inheritance, Polymorphism and the Object Memory Model

CS201 - Introduction to Programming Glossary By

CSE 303: Concepts and Tools for Software Development

Object-Oriented Principles and Practice / C++

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

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

Interview Questions of C++

CSE 307: Principles of Programming Languages

CS

Data Abstraction. Hwansoo Han

G Programming Languages - Fall 2012

Protection Levels and Constructors The 'const' Keyword

Pointers, Dynamic Data, and Reference Types

C++ Constructor Insanity

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

CS250 Final Review Questions

CPSC 427: Object-Oriented Programming

CS24 Week 3 Lecture 1

2 ADT Programming User-defined abstract data types

Absolute C++ Walter Savitch

CPSC 427: Object-Oriented Programming

Fast Introduction to Object Oriented Programming and C++

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Object-Oriented Programming

Lesson 13 - Vectors Dynamic Data Storage

CSE 12 Week Eight, Lecture One

CPS 506 Comparative Programming Languages. Programming Language

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

CE221 Programming in C++ Part 1 Introduction

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

B16 Object Oriented Programming

A brief introduction to C++

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

C++ Programming: Polymorphism

Object-Oriented Programming for Scientific Computing

10. Object-oriented Programming. 7. Juli 2011

G52CPP C++ Programming Lecture 13

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

Operator overloading. Conversions. friend. inline

EL2310 Scientific Programming

Object-Oriented Principles and Practice / C++

COMP 2355 Introduction to Systems Programming

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

Lecture 14: more class, C++ streams

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Ch. 10: Name Control

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

Constants, References

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

Inheritance, and Polymorphism.

Lecture 2, September 4

04-19 Discussion Notes

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Lecture 13: more class, C++ memory management

Object Oriented Software Design II

explicit class and default definitions revision of SC22/WG21/N1582 =

Polymorphism Part 1 1

Object-Oriented Principles and Practice / C++

#include <iostream> #include <cstdlib>

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

10. Functions (Part 2)

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Computer Science II CSci 1200 Lecture 18 Operators and Friends

STRUCTURING OF PROGRAM

Friend Functions and Friend Classes

And Even More and More C++ Fundamentals of Computer Science

PIC 10A Objects/Classes

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

COMP6771 Advanced C++ Programming

C The new standard

B16 Object Oriented Programming

Object Oriented Paradigm

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

CMSC 132: Object-Oriented Programming II

C++ (Non for C Programmer) (BT307) 40 Hours

QUIZ. What are 3 differences between C and C++ const variables?

EL2310 Scientific Programming

CPSC 427a: Object-Oriented Programming

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

GEA 2017, Week 4. February 21, 2017

Software Development with C++ Templates

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

CS250 Final Review Questions

Transcription:

From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3 Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

C++ Values, References, and Pointers 1 C++ Values, References, and Pointers 2 C++ Classes 3 Construction in C++

C++ Values, References, and Pointers C++ Type System Java: primitive values, class references. Value type T C++: Pointer type T* Alias type T& Prefixing const makes a new type. We will prefer pointers to references/aliases, except for employing the type const T& for certain parameters and special constructors. We will use all of: const T* xp Pointer to constant T T* const xp Constant pointer to T const T* const xp Const ptr to const T

C++ Values, References, and Pointers What is a Java reference? In Java, Foo x = new Foo() creates two items: x 5004 5004 anobj. This == what you get with the C++ declaration Foo* x = new Foo() In both languages, the name x is bound to an integer object whose value is the memory address of an unnamed Foo object. Java hides this pointer value ; C++ doesn t.

C++ Values, References, and Pointers C++ References are Just Aliases C++ references are disembodied pointers they don t have the 5004 part at all. Main operational difference from Java references: If you do string xhost = "Jello"; string yhost = "Bello"; string& xr = xhost; string& yr = yhost; yr = xr; xr[0] = H ; cout << xr << " " << yr << " " << xhost << endl; you get yr = "Jello", whereas with pointers and Java references, yr = xr; does not copy the contents of xr. One cannot initialize a non-constant reference to a pure value, only to the variable beign aliased. Note that xhost is not copied, and winds up saying "Hello" too.

C++ Values, References, and Pointers Pointers and Const Foo y; //when value, NO (), would look like function const Foo* xpcd = new Foo(); Foo* const xcp = new Foo(); xpcd = &y; //OK xpcd->meth(); //OK *if* meth is const! //xcp = &y; //can t reassign Foo* const xcp->mutate(); //OK And const Foo* const xcpc = new Foo(); tells the compiler that xcpc cannot be re-assigned, and that the anonymous Foo object cannot be modified through xcpc (though it could be modified thru a non-const pointer, a hole which some newer OO languages try to fill). [HelloConst.cpp illustrates this with strings.]

C++ Values, References, and Pointers C++ const and Java final On primitive types they are equivalent, e.g. const double PI = 3.14159; A Java final reference is equivalent to a C++ constant pointer, but not a pointer to constant data. On methods, the meanings are perpendicular: C++ const methods can be overridden. C++ const methods cannot modify the invoking object at least not its top-level fields. ( Deep Const is a current research issue.) (A field that is not really part of the constant state of the object can be marked mutable, to allow const methods to change it!)

C++ Values, References, and Pointers Why C++? C++ compilers are smarter than Java compilers are allowed to be. C++ gives programmers more control over how objects are laid out: on the stack as values, vs. on the heap via pointers, by user-managed memory, by packing and assembly-level tricks. C++ allows more-efficient code. C++ has more-advanced O-O features (except that it does not yet have Java s template bounds). Most working code is in C++, and will be for a long time.

C++ Classes Java to C++: Foo x = new Foo(a,b); Foo* xp = new Foo(a,b); x.field, x.method(); xp->field, xp->method(); Also legal are (*xp).field, (*xp).method Assignment: x = y; xp = yp; no change because a Java reference assignment is overtly the same as a C++ pointer assignment.

C++ Classes Translating Java Classes Trailing ; after class-closing brace } extends becomes : public public, private, and protected denote regions, not individual items. Can alternate repeatedly... No default/package scope instead write friend class Bar; within class Foo, to enable class Bar to access internals of class Foo. One can also declare a global function to be a friend we will reserve this almost exclusively for operators associated to classes such as operator<< in example files LinkArg.{h,cpp}. C++ namespaces are like Java packages, and provide a prefix to avoid ambiguity, e.g. std::cout Between class (or namespace) and field, C++ uses :: not Java.

C++ Classes Translating Within Classes Put virtual before a method meth to get Java behavior when you call meth thru a pointer! If meth is an accessor i.e., cannot change the object that invokes it then it should have const after the method parameters. Method code can be inlined like in Java, but for all but tiny bodies, putting the method header in a Foo.h file and the body in a separate Foo.cpp file is preferred. (Recitations next week will focus on code files.) Special syntax for constructors and The Big Three...

C++ Classes Member Differences Can t initialize non-constant fields outside constructor. Can use this->x akin to this.x in Java. Accessor methods should must! have const right after their parameters. No keyword abstract instead C++ marks abstract member functions (which must be virtual) by appending = 0; to them nulling out their function pointers! A class is abstract if it has an abstract method.

C++ Classes No Interfaces!? C++ has unrestricted multiple inheritance: class Foo: public Bar, Com, Delta {... So one can get the effect of a concrete interface by: class Comparable { public: virtual int compare(const Comparable& rhs) const = 0; }; Note the const & parameter idiom, and the abstract method itself being const. (No const after & is needed const references already can t be on LHS of any assignment.)

C++ Classes C++ Templates Are Real Code Java class Foo<T> {... becomes C++ template<typename T> //say class T if T should be a class class Foo { //NOT "class Foo<T>" as in Java-->weird errors!... Foo(...)... //constructors MAY do "Foo<T>", but text doesn }; template<typename T> //must repeat for bodies outside class Foo<T>::Foo(..){..} //first <T> required, second MIGHT be error! Declarations in the body of Foo that use T should have typename in front. Major difference from Java: C++ generates separate object code for Foo<Bar> and Foo<Com> etc. To save code bloat, Java erases the template after compile time and generates just Foo.class, but you can t tell at runtime whether a client is Bar or Com or etc.

C++ Classes C++ Templates Are Not Real Code If you have a template class Foo, compiler will let you put declarations in Foo.h and bodies in Foo.cpp, and even do CC -c Foo.cpp to create Foo.o. However, Foo.o does not really have object code instead, when a client file Bar.cpp (or Main.cpp or etc.) instantiates a Foo<Bar> object, the object code for Foo<Bar> is embedded into Bar.o (or, put in a separate templates repository as the Sun CC compiler used to do, or etc.). Thus Foo.o is not real code, so all template classes are morally headers. More to the point: With g++ (still) and many other compilers, linking will fail if Foo.cpp is separate from Foo.h and only the latter is included. Hence we will require that template bodies be in the same file, either inside or outside the template class braces. (I ve read that outside can cause another problem, but haven t gotten it with any compiler, and whole previous CSE250 years were not affected.)

C++ Classes No Interface Bounds! Java has class Foo<T extends Comparable> {... to ensure that any valid argument Bar for T defines int Bar.compare(Comparable rhs). C++ doesn t do this a proposal called Concepts was dropped from next-update plans in July (2009)! If a client Bar fails to implement Compare, a file building a Foo<Bar> may still compile separately leaving the fault to be found at link time. Our g++ on timberlake seems to be more proactive. Please try the dompare typo in the files Link*.* in.../java2c++/ on your home systems. Later, we will do better by passing a function object for compare when constructing Foo. (Cf. COMP at bottom of p300 in text.)

C++ Classes A Java 5 Idiom to Know interface Comparable<T extends Comparable<T>> { public int compare(t rhs); } class Bar extends Comparable<Bar> { public int compare(bar rhs) {... }... } class Foo<T extends Comparable<T>> { //Bar OK as T...aMethod(T[] args) {...if (args[i].compare(args[j]) < 0) {... } }... } //generic T[] array OK as parameter in Java, can t construct one The difference is that if a different class Delta extends Comparable, now you get a compile-time error if you mistakenly do bar.compare(delta), instead of a runtime exception. Java 5 convulsed the language to achieve this. C++ templates and linking do this, but less explicitly.

Construction in C++ Constructors C++ constructors use special initialization syntax: struct Point { //struct => top region is public double x, y; Point(double x, double y) : x(x), y(y) { } }; In Java you would write this.x = x; and this.y = y; as the first 2 lines inside the {...} of the constructor. The C++ system attempts to default-construct all fields of a C++ class that are NOT mentioned in the : part before the opening { is hit wasting time and sometimes causing havoc! So, use the : syntax.

Construction in C++ No Constructor Forwarding Unlike in Java, a C++ constructor may not call another, not even with the initialization syntax (as in C#). When a class has many fields, and different constructors must be provided, this forces ugly code duplication... at least of the field-initialization syntax. Forwarding is proposed for the next C++ revision, but it s being stalled by disagreement over when an object can be considered constructed : when the last (i.e., initially called) constructor exits? when the first constructor exits? when the initially-called constructor finishes its initialization syntax and starts on its body (if any)? (my preference!)

Construction in C++ The Big Three Usually needed only when a class allocates memory, or when the default field-by-field destruction/clone/copy is not the desired behavior... [virtual] ~Foo(...) {...} Foo(const Foo& rhs) {...} //destructor //copy constructor Foo& operator=(const Foo& rhs) {...} //assignment... but even if a base class does not allocate memory and does not have any virtual methods, it should define a (trivial) virtual destructor to allow subclasses to do so. More in lectures later, chs. 3 4.

Construction in C++ Implicit Conversions A single-argument constructor Foo(Bar bar) automatically gets invoked when you write foo = bar;...... unless you prevent this dangerous behavior by putting the keyword explicit before the constructor s declaration. A class Foo can also define an implicit conversion the other way via: operator Bar() const {... return bar; } Both kinds apply in assignments and parameter calls, but not stream operators see LinkArg.{h,cpp}.

Construction in C++ Summary of Java2C++: Much of the line syntax is similar, differences-as-noted. File handling is different: {.h,.cpp}, #include, make... Recitations are emphasizing this and stream I/O. C++ has a richer type system, and the notion of value differs from Java on non-primitive types. And there are C++ references, which I prefer to call aliases. They inhibit copying, provide assignment and streaming targets, and behave like values when read from. Class hierarchies are similar, but the Java default method behavior requires extra work in C++ to get: virtual, pointers... Templates have similar use to Java generics, but work differently under-the-hood... and give beastly errors...