'&$%CSE 303:Concepts and Tools for Software DevelopmentHal PerkinsSpring 2008Lecture 24— Introduction to C++CSE303 Spring 2008, Lecture 24 1'&$%C++C++ is an enormous language:• All of C• Classes and objects (kind of like J ava, some c rucial differences )• Many more little c onvenience s (I/O, new /delete , functionoverloading, 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 w ill focus on a couple themes rather than just a “big bag of newfeatures to memorize”...CSE303 Spring 2008, Lecture 24 2'&$%Our focusOOP in a C-like language may help you understand C and Java better?• We c an put objects on the stack or the heap; an object is not apointer to an object• Still have to manage memory manually• Still lots of ways to HCBWKMSCOD (hopefully crash, but whoknows – m ight silently c orrupt other data)• 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 (differentdefaults from Java)CSE303 Spring 2008, Lecture 24 3'&$%Hello World#include <iostream>int main() {// Use standard output stream cout// and operator << to send "Hello World"// and an end line to stdoutstd::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 inany file, ...CSE303 Spring 2008, Lecture 24 4'&$%CompilingNeed a different compiler than for C; use g++ on attu. Example:g++ -Wall -o hello hello.ccThe .cc extension is a convention (just like .c for C), but lessuniversal (also see .cpp, .cxx, .C).Uses the C preprocessor (no change there).Now: A few “niceties” before our real focus (classes and objects).CSE303 Spring 2008, Lecture 24 5'&$%I/OOperator << takes a “ostream” and (various things) and outputs it;returns the stream, which is whystd::cout << 3 << "hi" << f(x) << ’\n’; works• Easier and safer than printfOperator >> takes “istream” and (various things) and inputs into it.• Easier and safer than scanf. Do not use pointers; e.g.,int x; std::cin >> x;Can “think of” >> and << as ke ywords, but they are not:• Operator overloading redefines them for different pairs of types.– In C they mean “left-shift” and “right-shift” (of bits);undefined for non-numeric types.• Lack of address-of for input done with call-by-reference (later).CSE303 Spring 2008, Lecture 24 6'&$%NamespacesIn 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 myspace { ... definitions ... }• Of course, then different namespaces can have the same functionnames and they are totally different functions.• Can nest them• Can reuse the same namespace in multiple places– Pariticularly common: in the .h and the .ccFor example, the whole C++ standard library is in namespace std.To use a function/variable/etc. in another namespace, dothespace::someFun() (not . like in Java)CSE303 Spring 2008, Lecture 24 7'&$%UsingTo avoid having to write namespaces and :: constantly, use a usingdeclarationExample:#include <iostream>using namespace std;int main() {cout << "Hello World" << endl;return 0;}CSE303 Spring 2008, Lecture 24 8'&$%Onto OOPLike Java:• Fields vs. methods, static vs. instance, constructors• Method overloading (functions, operators, and constructors too)Not quite like Java:• access-modifiers (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)CSE303 Spring 2008, Lecture 24 9'&$%Stack vs. heapJava: cannot stack-allocate an object (only a pointer to one).C: can stack-allocate a struct, then initialize it.C++: stack-allocate and call a constructor (where this is the object’saddress, as always)• Property p1(10000);Java: new Property(...) calls constructor, returns heap-allocatedpointer.C: Use malloc and then initialized, must free exactly once later.C++: Like Java, but can also do new int(42). Like C mustdeallocate, but must use delete instead of free.CSE303 Spring 2008, Lecture 24 10'&$%DestructorsAn object’s destructor is called just before the space for it is reclaimed.A common use: Reclaim space for he ap-alloc ated 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 he ap object,then reclaim space.Destructors also get called for stack-objec ts (w hen they le ave sc ope).Advice: Always make destructors virtual (learn why soon)CSE303 Spring 2008, Lecture 24 11'&$%ArraysCreate a heap-allocated array of objects: new A[10];• Calls default (zero-argument) constructor for each ele me nt.• 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 [] eElse HYCSBWK – the deleter must know somehow what is an array.CSE303 Spring 2008, Lecture 24 12'&$%Digression: Call-by-referenceIn C, we know function arguments are copies• But copying a pointe r means you still point to the same(uncopied) thingSame in C++, but a “reference parameter” (the & character after it)is different.Callee writes: void f(int& x) { x = x + 1; }Caller writes: f(y)But it’s as though the caller wrote f(&y) and everywhere the calleesaid x they really said *x.So that little & has a big meaning.CSE303 Spring 2008, Lecture 24 13'&$%Copy ConstructorsIn C, we know x=y or f(y) copies y (if a struct, then member-wisecopy).Same in C++, unless a copy- constructor is defined, then do whateverit says.A copy-constructor by definition t akes a reference parameter (e lse we’dneed to copy, but that’s what we’re defining) of the s ame type.Let’s not talk about the
View Full Document