3. Why C++?
โข Popular and relevant (used in nearly every application domain):
โ end-user applications (Word, Excel, PowerPoint, Photoshop, Acrobat,
Quicken, games)
โ operating systems (Windows 9x, NT, XP; IBMโs K42; some Apple OS X)
โ large-scale web servers/apps (Amazon, Google)
โ central database control (Israelโs census bureau; Amadeus; Morgan-
Stanley financial modeling)
โ communications (Alcatel; Nokia; 800 telephone numbers; major
transmission nodes in Germany and France)
โ numerical computation / graphics (Maya)
โ device drivers under real-time constraints
โข Stable, compatible, scalable
4. C vs. C++
โข C++ is C incremented
(orig., โC with classesโ)
โข C++ is more expressive
(fewer C++ source lines needed than C source lines for same program)
โข C++ is just as permissive
(anything you can do in C can also be done in C++)
โข C++ can be just as efficient
(most C++ expressions need no run-time support;
C++ allows you to
โ manipulate bits directly and interface with hardware without regard for safety
or ease of comprehension, BUT
โ hide these details behind a safe, clean, elegant interface)
โข C++ is more maintainable
(1000 lines of code โ even brute force, spaghetti code will work;
100,000 lines of code โ need good structure, or new errors will be
introduced as quickly as old errors are removed)
5. Efficiency and Maintainability
90/10 rule: 10% of your program will take 90% of the
processor time to run
๏ optimize what needs to be optimized, but no more
๏ focus on design
Efficiency
(processor time)
Maintainability
(programmer time)
6. Design goals of C++
โข Backward compatibility with C
(almost completely โ every program in K&R is a C++ program โ
but additional keywords can cause problems)
โข Simplicity, elegance
(few built-in data types, e.g., no matrices)
โข Support for user-defined data types
(act like built-in types; N.B. Standard Template Library (STL))
โข No compromise in efficiency, run-time or memory
(unless โadvanced featuresโ used)
โข Compilation analysis to prevent accidental corruption
of data
(type-checking and data hiding)
โข Support object-oriented style of programming
7. Compatibility with C
C++ does not allow
โข old-style C function declarations
void f(a) int a; {}
โข generic function declarations
void f();
void g() { f(2); }
โข setting enum to int
enum Dir {Up, Down}; Dir
d=1;
โข multiple declarations
int i; int i;
โข assigning to void *
int* p = malloc(10);
โข โimplicit intโ
signed a = 7;
Other differences:
โข const global variables have
internal linkage in C++,
external in C
โข extra keywords in C++
void main()
{ int catch = 5; }
โข bizarre comments
int f(int a, int b)
{
return a//**/b
;
}
How is C++ not backward compatible with C (C89)?
(For these, C++ is backward
compatible with C99)
8. Purpose of a programming
language
โข Programming languages serve two
purposes:
โ vehicle for specifying actions to be executed
โclose to the machineโ
โ set of concepts for thinking about what can
be done
โclose to the problem being solvedโ
โข Object-oriented C++ excels at both
9. Learning C++
โข Goal: Donโt just learn new syntax, but become a
better programmer and designer; learn new and
better ways of building systems
โข Be willing to learn C++โs style; donโt force
another style into it
โข C++ supports gradual learning
โ Use what you know
โ As you learn new features and techniques, add those
tools to your toolbox
โข C++ supports variety of programming paradigms
10. Programming paradigms
โข procedural โ implement algorithms via
functions (variables, functions, etc.)
โข modular โ partition program into modules
(separate compilation)
โข object-oriented โ divide problem into classes
(data hiding, inheritance)
โข abstract โ separate interface from
implementation (abstract classes)
โข generic โ manipulate arbitrary data types
(STL: containers, algorithms)
11. โข Encapsulation
โblack boxโ โ internal data hidden
โข Inheritance
related classes share implementation
and/or interface
โข Polymorphism
ability to use a class without knowing its type
What is object-oriented?
ยฉ SDC
โC++ is an object-oriented languageโ =
C++ provides mechanisms that support object-oriented style of
programming
12. Some C++ concepts
โข constructor / destructor / copy constructor
โข initialization list
โข inheritance
โข exceptions
โข overloading operators (e.g., assignment operator)
โข namespace
โข const
โข virtual function
โข pure virtual (abstract) function
โข friend
โข template
โข standard template library (STL)
โข pass by value, pass by reference
โข composition versus derivation
13. A simple C++ program
#include <iostream> // std::cout
#include <cstdio> // printf
int main()
{
int a = 5; // 'a' is L-value
float b = 0.9f;
printf("Hello world %d %3.1f n", a, b);
std::cout << "Hello world" << a << " "
<< b << " " << std::endl;
return 0;
}
14. Declarations and definitions
โข Declaration:
โ extern char c;
โ struct User;
โ double sqrt(double);
๏ Okay to have many
โข Definition:
โ char c;
โ int count = 1;
โ double abs(double a) {
a>0 ? a : -a;
}
๏ Must have exactly one
15. Fundamental types
โข bool (true ๏๏ 1, false ๏๏ 0)
โข char (could be signed or unsigned
โ implementation-defined)
โข int (signed by default)
โข double
โข void (โpseudo-typeโ)
โข enum
โข class
โข also short, long, struct, float,
wchar_t, etc.)
Do not rely on sizes of these!
(Implementation-dependent)
INTEGRAL
ARITHMETIC
USER-DEFINED
16. Macros
โข Dangerous:
โ compiler never sees them
source code ๏ translation unit
โ global
โข Instead, use
โ const
โ inline
โ template
โ enum
โข Ok to use for include guards (โheader wrappersโ)
โข If you must use a macro, give it a long ugly name with
lots of capital letters
Example:
template<typename T>
inline T max(T t){
t>0 ? t : -t;
}
17. Memory allocation
โข โon the stackโ
โ block delimited by {}
โ object alive till it falls out of scope
โ calls constructor / destructor
โข โon the heapโ
โ new and delete replace malloc, calloc, free
โ object exists independently of scope in which it was created
โ also โon the free storeโ or โallocated in dynamic memoryโ
โ be careful: new ๏ delete, new[] ๏ delete[]
โ for safety, same object should both allocate and deallocate
โข โlocal static storeโ void foo() {
static int i=0;
}
18. Global variables
โข Built-in types initialized to 0
(but local variables uninitialized)
โข Initialized before main() invoked
โข Initialization order:
โ within translation unit, same as definition
โ between translation units, arbitrary order
file1.cpp
double pi = 3.14;
file2.cpp
double twopi = 2*pi;
Bad!
No guarantee that twopi
will be initialized correctly
19. A class
class Date {
public:
enum Month {Jan, Feb, Mar, ...}
Date(int year, Month month, int day);
int GetDay() const;
void SetDay(int day);
Date& operator+=(int days);
private:
Month m_month;
int m_year, m_day;
};
member
functions
(methods)
member
variables
20. Struct vs. class
โข In C++, no difference b/w struct and class
(except default public vs. private)
โข In C++, struct can have
โ member variables
โ methods
โ public, private, and protected
โ virtual functions
โ etc.
โข Rule of thumb:
โ Use struct when member variables are public (just a
container)
โ Use class otherwise
21. OO in C
โข In C, a struct can have
both member variables
and methods:
โข In C++, syntax is
simpler:
void CreateFoo()
{
}
struct Foo
{
void (*Construct)();
int m_data;
};
int main()
{
struct Foo a;
a.Construct = &CreateFoo;
a.Construct();
}
struct Foo
{
Foo()
int m_data;
};
Foo::Foo()
{
}
int main()
{
Foo a;
}
22. Names
โข Maintain consistent naming style
โ long names for large scope
โ short names for small scope
โข Donโt start with underscore; reserved for
special facilities
โข Avoid similar-looking names: l and 1
โข Choosing good names is an art
23. Access control
โข Public: visible to everyone
โข Private: visible only to the implementer of
this particular class
โข Protected: visible to this class and derived
classes
โข Good rule of thumb:
โ member functions (methods):
โข if non-virtual, then public or protected
โข if virtual, then private
โ member variables should be private
(except in the case of a struct)
24. The big four
โข By default, each class has four methods:
โ constructor Date();
โ destructor ~Date();
โ copy constructor
Date(const Date& other);
โ assignment operator
Date& operator=(const Date& other);
โข These call the appropriate functions on each
member variable
โข Be careful: If this is not what you want, then
either override or disallow (by making private)
25. Constructor and destructor
โข (Copy) constructor creates object
โข Destructor destroys (โcleans upโ) object
โข Be aware of temporary objects
class Matrix {
Matrix(const Matrix& other);
Matrix operator+(const Matrix& other) const;
Matrix& operator=(const Matrix& other);
};
void foo() {
Matrix a, b, c, d;
a = b + c + d;
}
What functions get called?
(Note: There are ways to speed this up while preserving the syntax)
26. Example
Suppose we have a simple class.
class A {
public:
A() { printf("conn"); }
A(const A& other) { printf("copyconn"); }
~A() { printf("desn"); }
A& operator=(const A& other) { printf("assignn");
return *this;
}
};
27. Example 1
What is the output of the following program?
01 {
02 A a;
03 A* b = new A();
04 *b = a;
05 delete b;
06 A c = a;
07 }
02 con
03 con
04 assign
05 des
06 copycon
07 des
07 des
28. Example 2
What is the output of the following program?
01 void F(const A& f, A* g, A h)
02 {
03 *g = f;
04 }
05 {
06 A a, b;
07 F( a, &b, a);
08 }
06 con
06 con
01 copycon
03 assign
04 des
08 des
08 des
29. Example 3
What is the output of the following program?
01 A F()
02 {
03 A tmp;
04 return tmp;
05 }
06 {
07 A a = F();
08 }
(VC++ 6.0 -- Windows)
03 con
07 copycon
05 des
08 des
(g++ 3.4.3 -- Linux)
07 con
08 des
30. Avoid new and delete
โข Whenever possible, avoid โnewโ and โdeleteโ
โข Instead create object on stack
โข Automatic destructor makes things easier
โข No need to worry about forgetting to delete the
object (memory leak) or deleting the wrong
object (crash)
โข If you must use โnewโ, then try to keep the
โdeleteโ nearby
โข This helps code maintenance โ otherwise it is
hard to keep track of the new/delete pairs
31. When to use new and delete
โข Sometimes you have to use new and
delete
โข And sometimes the pair cannot be close
together
โข Oh well
โข The next slide shows an example where
we need to break both of these rules
32. An example of new/delete
โข You have a base class:
class Command { virtual DoSomething(); };
โข You have several derived classes:
class CommandAdd : public Command {};
class CommandMove : public Command {};
class CommandSet : public Command {};
โข You have a list of objects whose types are unknown at compile
time (polymorphism):
std::vector<Command*> undo_list;
โข Must put pointers in list โ not actual objects โ because the objects
may be of different sizes (among other reasons)
โข Someone creates the object and puts its pointer on the list:
undo_list.push_back( new CommandAdd() );
โข Later the object is removed from the list and deleted:
Command* com = undo_list.back();
undo_list.pop();
com->DoSomething(); // call a virtual method
delete com;
34. Concrete classes
โข A concrete class
โ does a single, relatively small thing well and
efficiently
โ hides data members (encapsulation)
โ provides clean interface
โ acts like a built-in type
โ is a โfoundation of elegant programmingโ โ
Stroustrup
โข Donโt underestimate the importance of this
basic C++/OO feature!
35. Class relationships
โข OK:
โ A calls function from B
โ A creates B
โ A has a data member of type B
โข Bad:
โ A uses data directly from B
(without using Bโs interface)
โข Even worse:
โ A directly manipulates data in B
36. Pointers, arrays, references
โข Use 0, not NULL (stronger type checking)
โข Name of array is equivalent to pointer to
initial element
โข Access array using * or []; same
efficiency with modern compiler
โข use std::vector, not built-in array,
when possible
โข Reference is like a pointer
37. References
โข Reference: alternate
name for an object (alias)
โข There is no
null reference
โข No reference to
a temporary
โข Syntax confusing
โข Basically a const
dereferenced pointer
with no operations
int &a;
int* c = &a;
int& a = 1;
โget address ofโ
(not a reference)
int b; int &a = b;
(Now use โaโ as โbโ)
38. Confusing syntax
int a, b;
int c = a * b;
int* d = &a;
int e = *d;
int& f = a;
* means
โข multiplication, or
โข pointer, or
โข dereference pointer
& means
โข get address of, or
โข reference
Same symbol, different meanings!
39. Pass by X
void f(int a, int* b, int& c)
{
// changes to a are NOT reflected outside the function
// changes to b and c ARE reflected outside the function
}
main()
{
int a, b, c;
f(a, &b, c);
}
pass
by
value
pass
by
pointer
pass
by
reference
DOES
make a copy
does NOT
make a copy
PBP and PBR are different syntax for the same functionality
40. Argument passing / return
โข Pass / return by value
โ calls copy constructor
โ ok for built-in types
int foo(int a) { return 0; }
โ performance penalty for structs and classes (temporary objects)
โข Pass / return by reference or pointer
โ does not call copy constructor
โ pass inputs by const reference
โ never pass inputs by โplainโ reference
void update(int& a); update(2); // error
โ pass outputs by pointer
int x = 1; next(x); // should not change x
int x = 1; next(&x); // may change x
โ ok to return a ref, or const ref
41. C++ function mechanisms
โข Overloaded function names
โ Cleaner and safer
print(int);
print(float);
โ But beware
print(int); print(int*); print(0);
โข Default parameters
void print(int a, int b=0, int c=0);
โข Operator overloading
Matrix& operator+=(const Matrix& other);
โข Implicit conversion operator
operator int() const {} // converts to int
โ Provides convenient syntax, but potentially dangerous so use
sparingly
42. Opaque pointers
โข An opaque pointer is used to hide the internal
implementation of a datatype
โข Also called Pimpl (pointer to implementation) idiom, or
Cheshire Cat
โข Example: The d-pointer is the only private data
member of the class and points to an instance of a
struct defined in the class' implementation file
http://en.wikipedia.org/wiki/Opaque_pointer
43. Explicit type conversion
โข C++ casts
โ static_cast between 2 related types
(int/float, int/enum, 2 pointers in class hierarchy)
โ reinterpret_cast between 2 unrelated types
(int/ptr, pointers to 2 unrelated classes)
โ const_cast cast away constness
โ dynamic_cast used for polymorphic types
Run-time type info (RTTI)
โข Avoid casts, but use these instead of C casts
โ e.g., compiler can perform minimal checking for
static_cast, none for reinterpret_cast
44. Namespaces
โข Namespace expresses logical grouping
โข using declaration
โ Donโt use global using except for transition to
older code
โ Ok in namespace for composition
โ Ok in function for notational convenience
โข Namespaces are open
โข Unnamed namespaces restrict code to local
translation unit
โข Aliases ( namespace ShortName = LongName; )
45. Const
โข Const prevents object from being modified (orig., readonly)
โข Avoid magic numbers
char a[128];
const int maxn = 128;
char a[maxn];
โข Logical constness vs. physical constness
โข Const is your friend; use it extensively and consistently
โข can cast away constness, but be sure to use mutable
โข const pointers:
โ const int * const ptr = &a[0]; // const ptr to a const int
โ int const * const ptr = &a[0]; // โ
โ int * const p2 = &a[0]; // const ptr to an int
โ const int * p1 = &a[0]; // ptr to a const int
โ int const * p2 = &a[0]; // โ
46. Assert macro
โข Assert allows the programmer to explicitly type assumptions
about expected inputs and values
โข Use assert generously; it is your friend
โข Assert helps to catch bugs early during development
โข Assert is removed by precompiler before final release, so no run-
time penalty
โข Use assert only to check values; do not change values!!!
#include <assert.h>
int GetValue(int index)
{
assert(index >= 0 && index < array.size());
if (index < 0 || index >= array.size())
return -1; // value should make sense
return array[index];
}
If performance is not a concern,
then it is okay to augment (but
not to replace) assert with an
extra check that will remain in
the final version.
47. Inheritance
โข Subclass derived from base class
โข Two classes should pass the โISAโ test:
derived class is a base class
class Shape {
};
class Circle : public Shape {
};
โข Class hierarchy: means of building classes
incrementally, using building blocks
(subclass becomes base class for someone else)
โข Facilitates code reuse
48. Inheritance vs. composition
โข Inheritance: โis aโ
class Circle : public Shape {
};
โข Composition: โhas aโ
class Circle {
private:
Shape m_shape;
};
โข Decision should be based on commonality of
interface
49. Virtual functions
โข Function of derived class is called even if you have only a pointer to the base class
File.h
class Shape
{
virtual void Draw();
};
class Circle : public Shape
{
virtual void Draw();
};
File.cpp
void Func1()
{
Circle mycirc;
Func2(&mycirc);
}
void Func2(Shape* s)
{
s->Draw();
}
// calls Circle::Draw()
50. How a virtual function works
Shape vtable
vfunc1 addr
vfunc2 addr
...
vfuncN addr
vfunc1 addr
vfunc2 addr
...
vfuncN addr
Circle vtable
var1
...
varM
vtable ptr
mycirc
var1
... varN
shape member
variables
circle member
variables
{
{
51. What is the penalty of a virtual
function?
โข Space:
โ one vtable per class with virtual function(s)
โ one pointer per instance
โข Time:
โ one extra dereference if type not known at
compile time
โ no penalty if type known at compile time
(ok to inline a virtual function)
52. Pure virtual function
โข Pure virtual function
โ Function intentionally undefined
โ Same penalty as regular virtual function
โข Abstract class
โ Contains at least one pure virtual function
โ Cannot instantiate; must derive from base class and override pure virtual
function
โ Provides an interface
(separates interface from implementation)
โข Advice: virtual functions should always be pure virtual
โ i.e., โMake non-leaf classes abstractโ (Scott Meyers, Item 29)
โ Also, โDonโt derive from concrete classesโ (Herb Sutter, p. 137)
โข More advice: Make virtual functions private (Herb Sutter, p. 134). This
separates the override implementation details from the public interface.
class Shape {
virtual void Draw() = 0;
};
53. Multiple inheritance
โข C++ allows you to inherit from multiple
base classes
โข Works best if
โ exactly one base class passes ISA test
โ all other base classes are interfaces
โข Advanced feature that is rarely needed
class MyDialog :
public CDialog, Observer {};
MyDialog is a CDialog
MyDialog needs a single method
from Observer (lightweight class)
(see MVC architecture)
54. Polymorphism
โข Polymorphism
โ โability to assume different formsโ
โ one object acts like many different types of objects
(e.g., Shape*)
โ getting the right behavior without knowing the type
โ manipulate objects with a common set of operations
โข Two types:
โ Run-time (Virtual functions)
โ Compile-time (Templates)
55. Exceptions
โข Error handling in C:
โ Half of code is error handling
โ Dangerous: Easy for programmer to forget
to check return value
void Func() {
int ret;
ret = OpenDevice();
if (ret != 0) error(โUnable to open deviceโ);
ret = SetParams();
if (ret != 0) error(โUnable to set paramsโ);
}
57. Templates
โข Define a class or function once, to work with a variety
of types
โข Types may not be known until future
โข Better type checking and faster (cf. qsort)
โข Specialization can be used to reduce code bloat
โข Templates support generic programming
template<typename T>
T Max(T a, T b) { return a>b ? a : b; }
template<typename T>
class Vector {
Vector(int n, T init_val);
T* m_vals;
};
58. Generic programming
โข Drawbacks of qsort in <stdlib.h>
โ requires a compare function, even if trivial
โ loss of efficiency b/c dereferencing pointer
โ lost type safety b/c void*
โ only works with contiguous arrays
โ no control over construction / destruction /
assignment; all swapping done by raw
memory moves
59. Standard Template Library (STL)
โข Containers:
โ Sequences
โข vector โ array in contiguous memory (replaces realloc)
โข list โ doubly-linked list (insert/delete fast)
โข deque (โdeckโ) โ double-ended queue
โข stack, queue, priority queue
โ Associative
โข map โ dictionary; balanced tree of (key,value) pairs
like array with non-integer indices
โข set โ map with values ignored (only keys important)
โข multimap, multiset (allow duplicate keys)
โ Other
โข string, basic_string โ not necessarily contiguous
โข valarray โ vector for numeric computation
โข bitset โ set of N bits
61. std::string
โข Example:
#include <string>
void Func()
{
std::string s, t;
char c = 'a';
s.push_back(c); // s is now โaโ;
const char* cc = s.c_str(); // get ptr to โaโ
const char dd[] = "afaf";
t = dd; // t is now โafafโ;
t = t + s; // append โaโ to โafafโ
}
62. std::vector
#include <vector>
void Func()
{
std::vector<int> v(10);
int a0 = v[3]; // unchecked access
int a1 = v.at(3); // checked access
v.push_back(2); // append element to end
v.pop_back(); // remove last element
size_t howbig = v.size(); // get # of elements
v.insert(v.begin()+5, 2); // insert 2 after 5th element
}
โข Example:
63. std::vector (cont.)
#include <vector>
#include <algorithm>
void Func()
{
std::vector<int> v(10);
v[5] = 3; // set fifth element to 3
std::vector<int>::const_iterator it
= std::find(v.begin(), v.end(), 3);
bool found = it != v.end();
if (found) {
int three = *it;
int indx = it - v.begin();
int four = 4;
}
}
โข Example:
64. Iterators
โข iterator โ generalized pointer
โข Each container has its own type of
iterator
void Func() {
stl::vector<int> v;
stl::vector<int>::const_iterator it = v.begin();
for (it = v.begin() ; it != v.end() ; it++) {
int val = *it;
}
}
65. Types of iterators
template<class InputIterator, class Type>
InputIterator
find( InputIterator _First,
InputIterator _Last,
const Type& _Val );
โข Each container provides a
different type
input
forward
bidirectional
random access
output
Types
66. Allocators
โข STL written for maximum flexibility
โข Each container has an allocator
โข Allocator is responsible for memory
management (new/delete)
template < class Type,
class Allocator = allocator<Type> >
class vector {
...
};
โข Advice: Ignore allocators
67. Streams
โข C
โ flush, fprintf, fscanf, sprintf, sscanf
โ fgets, getc
โข C++
โ cout, cin, cerr
68. Buffer overrun
โข Never use sprintf!
โข Use snprintf instead to avoid buffer
overrun
โข Or use std::stringstream