C++ Crash Course

advertisement
C++ Crash Course
For CS184 Sp08
Trevor Standley
C++ Is ~(C+Java)/2
 Comprises a combination of both high level
and low level language features
 Developed in 1979 at Bell Labs as an
enhancement to the C programming language
 Developed for backward compatibility with C
 First named, “C with Classes”
 Blazing fast, just like C. Direct access to RAM
 Classes, polymorphism, exception handling,
strong typing, templates, operator overloading
etc
 No memory management
Common Complaints
“C++ is not a high level language.”
“Memory management… Yuck!”
“I hear that it’s complicated, and messy.”
“It was designed for compatibility with an
ancient language, certainly the designers of
modern languages could have done better
without this restriction.”
 “I don’t like C, why should I like C++?”
 “Who knows C++?”




Hello World




#include <iostream>
using namespace std;
int main()
{
 cout << “Hello World” << endl;
 return 0;
}
Object vs Reference
 Consider the following:
 swap(int &a, int &b)
 {
 int t = a;
 a = b;
 b = t;
 }
Creating an Object
 C++
 vector<int> vec;
 vec.push_back(6);
 vector<int> vec2 = vec; //deep copy
 vector<int> *vec = new vector<int>();
 vec->push_back(6);
 vector<int> *vec2 = vec; //shallow copy
 Java
 Vector<integer> vec = new Vector<inte
ger>();
classes
Inheritance
Operator Overloading
Default Class Pieces
 foo has a destructor
 ~foo(){}
 a copy constructor
 foo(const foo &f){x = f.x;}
 an assignment operator
 foo operator = (const foo &f)
 {
 x = f.x;
 }
 Possibly others
Templates
Memory Management
 Take a deep breath, you probably
won’t have to do any.
 C++ uses the “Resource
Acquisition Is Initialization”
paradigm
 Clean up after yourself.
Memory Management 2
 Most memory is managed
automatically when an object is
initialized or goes out of scope
 The only exception is when the new
operator is used.
 Standard libraries manage their own
memory
 If you use new, use delete
The Syntax
 new returns a pointer to a location in
memory where the requested object
is
 int *x = new int[5]; // returns a
pointer to memory where 5 ints are
 delete [] x;
 x = new vector2d(3,5)
 delete x;
Memory Management Example 1
Memory Management Example 2
The Standard Template Library
 C++ has multiple inheritance, which
has little meaning in practice except
that the STL is awesome!
 std::vector: include <vector>
 std::list: include <list>
 std::string : include <string>
 std::stringstream : include
<sstream>
 Etc.
More Information
 http://www.cplusplus.com/
 http://en.wikipedia.org/wiki/C%2B%
2B
 http://en.wikipedia.org/wiki/Compari
son_of_Java_and_C%2B%2B
Download