Object Oriented Programming and C++
2009
Introduction
C++ Compared to Java Roger B. Dannenberg, Ph.D. Associate Research Professor School of Computer Science Carnegie Mellon University
Overview
History of C and C++ Differences between C++ and Java Why Use C++? Plans for the course
2009, Roger B. Dannenberg
History of C
Originally, compilers and operating systems were written in assembler Several efforts to get away from machine code for systems programming Dennis Ritchie wrote C for PDP-11, 1972 Closely connected with creation of Unix C code is
Fast Low-level (access to addresses, bits, raw bytes) Fairly portable -- driven by efforts to port Unix
ANSI C standard introduced in 1989
2009, Roger B. Dannenberg 3
History of C++
As C was being standardized, Object oriented programming was taking hold Need for systems programming language supporting OOP Several efforts based on macros, precompilers, etc. Bjarne Stroustrup led an effort resulting in C++ C++ became immensely popular Standardization efforts followed
2009, Roger B. Dannenberg
Some C++ Characteristics
Most C programs can be compiled by C++ C++ adds but does not take away Very similar low-level semantics to C, just new stuff thrown on top, minimal new keywords Efficiency drives the design; dont give up efficiency of C Long evolution:
Big and (too) complex Buggy compilers until recently
2009, Roger B. Dannenberg 5
Java
James Gosling and group at Sun Microsystems Came after C++ Adopts much of C++ syntax Aims to simplify C++ Less language evolution, so Java features are more consistent with one another Emphasis on avoiding programming errors and avoiding unsafe programs
2009, Roger B. Dannenberg 6
C++ and Java Differences
Compiled vs. Interpreted Security and Robustness Multithreading API Differences
2009, Roger B. Dannenberg
Compiled vs. Interpreted
Java compiles to byte codes that are interpreted by a virtual machine Just-In-Time Compiler
Translate byte codes to machine code Cache and reuse translations
Java binaries can be portable C++ compiles to machine code
Usually 2 to 10x faster, but Java can be faster
C++ must be compiled for each OS and ISA (e.g. Linux/PPC, Linux/i386, Win32/i386)
2009, Roger B. Dannenberg 8
Security and Robustness
C++ can compute arbitrary machine addresses and read from them C++ pointers may be uninitialized, point to stale data, require programmers to free unwanted memory Java pointers are guaranteed to point to valid objects of the expected type, uses garbage collection C++ is not type-safe Java variables are guaranteed to be initialized
2009, Roger B. Dannenberg 9
Multithreading
A thread is essentially
A runtime stack A (virtual) processor with program counter, registers, condition codes Multiple threads can share memory
C++ programs obtain threads by systemdependent APIs (thread_create()) Java has threads built-in
But Java threads have some problems Semantics unclear, especially with modern multi-core processors
2009, Roger B. Dannenberg 10
APIs
Java is huge
Graphical user interface library Networking Database connectivity
C++ elects to separate the language from the libraries
Many libraries to choose from Vendors offer their own (incompatible) libraries
2009, Roger B. Dannenberg
11
Why Use C++
C++ is widely used Templates Operator overloading Standard Template Library (STL) Automatic reclamation of resources Conditional compilation Distinction between accessors and mutators Space efficiency Private inheritance
2009, Roger B. Dannenberg 12
C++ Is Widely Used
You will run into it and need to know it Large base of code in C++
If you write in C++, you can use C++ libraries Of course, same is true of Java So learn both!
Java can call C++
But you still really need to know it to use it
Some situations give you no choice
Device drivers almost always in C Java may limit real-time performance
2009, Roger B. Dannenberg 13
Templates
Programming where types can be parameters Useful for generic algorithms/classes
Linked list of T
Compiler generates code as needed Can provide better type checking than Java, although now Java has generics Can provide faster code than Java Warning: Templates can be painful!
2009, Roger B. Dannenberg 14
Operator Overloading
Operators such as + and * can be redefined Is this a good thing? Probably good sometimes
2009, Roger B. Dannenberg
15
Standard Template Library
Large, carefully implemented library for
Data structures (e.g. lists) Generic algorithms (e.g. sorting)
Of course, Java has a large library too We will discuss some differences later
2009, Roger B. Dannenberg
16
Automatic Reclamation of Resources
C++ provides alternatives to garbage collection (since it doesnt have GC) Local variables disappear when they go out of scope
C++ objects can be local variables C++ objects can do things like close files when they are destroyed: destructor methods
Shared objects can use reference counting
There are some programming patterns to automate reference count updates
Generally more work to manage memory, but More explicit management sometimes is an advantage, e.g. real-time systems
2009, Roger B. Dannenberg 17
Conditional Compilation
Compile-time values can enable/disable code Debugging vs Production versions of code Portability issues: compile different code depending on available API and OS Compile for different hardware variations Compile demo version
2009, Roger B. Dannenberg
18
Space Efficiency
C++ gives more control over memory use Data do not necessarily have extra fields for:
Run-time type information Garbage collection Length counts for arrays
Programmer can even lay out structures bit-by-bit
2009, Roger B. Dannenberg
19
Private Inheritance
Java supports only public inheritance C++ gives finer control over visibility of methods Programmer can express allowed usage and better express abstractions
2009, Roger B. Dannenberg
20
Why to Avoid C++ (Features)
C++ is big and complicated Too many features can lead to unreadable programs, obscure design Explicit pointer and memory management Easy to access invalid memory addresses
You can scribble on data by accident, bug becomes visible millions of instructions later Type errors circumvent compiler type checks
Bad interactions:
Must follow the rules but no automatic checks
2009, Roger B. Dannenberg 21
Memory Models: C++
Consider: s ruc t tper { son i ti ; n d i ty r n ea ; cha name[20] r ; } In C++, layout is very direct: i d yea r name
2009, Roger B. Dannenberg
22
Memory Models: Java
Consider: s ruc t tper { son i ti ; n d i ty r n ea ; cha name[20] r ; } In Java, addressable objects are not nested: i d yea r
name
2009, Roger B. Dannenberg
23
Memory Models
C++ Stack Frame Java Stack Frame
Obj1 Obj1 Obj2 Obj3 Obj3 Obj2
2009, Roger B. Dannenberg
24
Pointers and Garbage Collection
Garbage Collection (normally) requires:
Set of objects Pointers from within objects to other objects Pointer must reference a collectable object
No pointers to embedded objects No pointers to characters within strings No pointers to data within stack frames
Therefore,
Java objects are heap-allocated Almost no distinction between pointers and objects
C++ is different!
Pointers are rampant and highly visible Implications for language design and programmers
2009, Roger B. Dannenberg 25
C++ Misgivings
C++ is not a complete success Adherence to design philosophy led to serious problems Few people fully understand C++ (I dont) I believe that if understanding or debugging a C++ program requires detailed knowledge of C++, its best to change the program Many features of C++ should be avoided Nevertheless, Ive written 1000s of LOC in C++
2009, Roger B. Dannenberg 26
Plans for the Course
Programming projects Learning by doing Lectures
Highlight concepts Establish directions Warn about common pitfalls
Real learning will require
Reading the textbook and C++ references Programming
2009, Roger B. Dannenberg 27
Summary
C++ came before Java Widely used, important to know More emphasis on efficiency More machine-based memory model
2009, Roger B. Dannenberg
28