You are on page 1of 10

The C++ Language

The C++ Language Bjarne Stroupstrup, the language’s creator

C++ was designed to provide Simula’s


facilities for program organization together
Prof. Stephen A. Edwards with C’s efficiency and flexibility for systems
programming.

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

C++ Features Example: A stack in C


  
 
Classes
     !#" Creator function ensures stack
• User-defined types $% & '" is created properly.

Operator overloading (  )" Does not help for stack that is
automatic variable.
• Attach different meaning to expressions such as a + b
Programmer could
References
 )+*, -/.  inadvertently create
Pass-by-reference function arguments

 )0* 1" uninitialized stack.

Virtual Functions 324-/ )+*.5 6678-9 $:  7


-/) . .'"
• Dispatched depending on type at run time ;=< 02?>@"
Templates
/ , % 1"
(
• Macro-like polymorphism for containers (e.g., arrays)
Exceptions

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Example: A stack in C C++ Solution: Class


A=,37- A)0* .  OPRQSTSVUHWHQOXZY Definition of both
$
B-= +2C>.C7-=DE %  
67=FG=.@" O9[RQ\]S ^_UT`a=bcd representation and
/ , % ;9<A 1H; ; !'" e9f WZSTgd operations
(
gThTi9P e Oj Public: visible outside the class

I 7 $ J     -)0*A KLA=, I . UTWTQ/OX=kmlLYnSTgpoZqAdsr


$
B-= +2 2? ,=.C7 - DM I 8/
6 7F8G=.'" tu eHv gHh/S[=kwO[xQ\ytlzY Constructor: initializes

;=< H  N N!+2 I " eT{ kmS/gpoToZU/`a=bl}|\T\wu\/kx~RuHt| \ { Pxu€Rld


( S^STg‚/‚/cpo}t,d
Not clear these are the only stack-
r
related functions.
O9[RQ\]gugkwlƒY
Another part of program can modify any eT{ kmS/gpoToVqlV| \T\mu\/kR~Rh fxv | \ { PRux€ld
stack any way it wants to, destroying \„|HW/h=\ f S^m…H…HSTgTcd
invariants. r
Temptation to inline these
r d Member functions see object
computations, not use functions. fields like local variables
Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

1
C++ Stack Class C++ Stack Class
Natural to use Members (functions, data) can be public, protected,
or private
  )? =@"

 x  A
- xx.#"  ,-R.'" class Stack {
char s[SIZE];
A=, +2   x7-/.@" public:
char pop();
};
  )+* A)32 % =F   A)"
);=<   
- „.#" ) ;9<A  -x.'" Stack st;
st.s[0] = ‘a’; // Error: sp is private
A=, +2 ); <78-/.'" st.pop(); // OK

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Class Implementation Operator Overloading


C++ compiler translates to C-style implementation For manipulating user-defined “numeric” types

 75 6 J - K=.@KL 8-9.'"


C++ Equivalent C implementation
6A  + )? , ? )J  75 6 J 2  N#" Creating objects of the
=83   , !'"      !#"  2  N 1" user-defined type
$%  '" $%  '" Want + to mean
   6 $ 
( " something different in
)A-. this context
I 7 $ C  A- ,.@" I 7 $   ,  ),-/)*.@"
=8 7-/.'" I 7 $   ,  A-9  A) *'K =9.'"
( " A=,0  ,7,-/ )*.'" Promote 2.3 to a
complex number here

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Example: Complex number type References


C++’s operator overloading makes it elegant Designed to avoid copying in overloaded operators

 6  7 5 6 


A mechanism for calling functions pass-by-reference
7 6 'K $ 5 " C only has pass-by-value
 6 $  

 7 5 6  -/76 .@"


Pass-by-reference
void swap(int x, int y) { /* Doesn’t work */
 7 5 6  -/7
 6'KL76.'"
reduces copying

int tmp = x; x = y; y = tmp;


 7 5 6 J7 , 7TN 21-/ 7 % J 7 56 .'" }
( " void swap(int &x, int &y) { /* Works with references */
Operator overloading int tmp = x; x = y; y = tmp;
defines arithmetic
operators for the }
complex type
Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

2
Complex Number Type Complex Number Class
Member functions including operators can be defined Operators can also be defined outside classes
inside or outside the class definition
 75 6 C7,/78HN#-/7 % =  7 56 J'K
 75 6  7 % =  7 56   . 
 75 6
 

„7,97/N 2-/7 % J 75 6 A
 .  7 5 6    5?2? "
 0N2 '" // Copy constructor

/+N2?/'" / , %  5@" // invoke Complex::operator +=


$ C 5 N2? $ 5@" (
/ , % * $ "
(

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Function Overloading Const


Overloaded operators a specific case of overloading Access control over variables, arguments.
Rock of
General: select specific method/operator based on Provides safety Gibraltar
name, number, and type of arguments
const double pi = 3.14159265; // Compile-time constant

void foo(int); int foo(const char* a) { // Constant argument


void foo(int, int); // OK *a = ‘a’; // Illegal: a is const
}
void foo(char *); // OK
int foo(char *); // BAD: return type not in signature class bar { // “object not modified”
int get_field() const { return field; }
}

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Templates Template Stack Class


Our stack type is nice, but hard-wired for a single
W/|9gPRQTW/|OPRQ/SHSzO/PQ/STSVUW/Q/OXZY
LS^UT`Ra bcd
type of object e9f WZSTgd
T is a type argument
Using array of “void *” or a union might help, but
breaks type safety
gThTi9P e Oj
Used like a type within
C++ solution: a template class UTWTQ/OX=kmlLYnSTgpoZqAdsr the body
tu eHv gHh/S[=kVt9lƒY
Macro-processor-like way of specializing a class to eT{ kmS/gpoToZU/`a=bl}|\T\wu\/kx~RuHt| \ { Pxu€Rld
specific types S^STg‚/‚/cpo}t,d
r
Mostly intended for container classes LgHu/gkmlLY
eT{ kmS/gpoToVqlV| \T\mu\/kR~Rh fxv | \ { PRux€ld
Standard Template Library has templates for
\„|HW/h=\ f S^m…H…HSTgTcd
• strings, lists, vectors, hash tables, trees, etc. r
r d

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

3
Using a template Display-list example
Stack<char> cs; // Instantiates the specialized code Say you want to draw a graphical scene
cs.push(‘a’); List of objects
char c = cs.pop(); • lines, arcs, circles, squares, etc.

How do you store them all in a single array?


Stack<double *> dps; void *list[10]; // Ugly: type-unsafe
double d;
dps.push(&d); How do you draw them all?
switch (object->type) { // Hard to add new object
case LINE: /* … */ break;
case ARC: /* … */ break;
}
Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Inheritance Inheritance
Inheritance lets you build derived classes from base class Shape {
classes double x, y; // Base coordinates of shape
public:
void translate(double dx, double dy) {
class Shape { /* … */ }; x += dx; y += dy;
class Line : public Shape { /* … */ }; // Also a Shape }
Line inherits both the
}; representation and
class Arc : public Shape { /* … */ }; // Also a Shape
member functions of
class Line : public Shape { the Shape class
};
Shape *dlist[10];
Line l;
l.translate(1,3); // Invoke Shape::translate()

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Implementing Inheritance Virtual Functions


Add new fields to the end of the object class Shape { draw() is a virtual
virtual void draw(); function invoked
Fields in base class at same offset in derived class }; based on the actual
class Line : public Shape { type of the object, not
C++ Equivalent C implementation void draw(); the type of the pointer
};
6A  +   ?   class Arc : public Shape {
7
 6  KZ " 7
 6 @KZ void draw(); New classes can be
( " ( " }; added without having

 
to change “draw
6A  97
L     97 
Shape *dl[10];
 dl[0] = new Line;
everything” code
761K}F " 76 @KZ " dl[1] = new Arc;
( " 7
 6K}F " dl[0]->draw(); // invoke Line::draw()
( " dl[1]->draw(); // invoke Arc::draw()

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

4
Implementing Virtual Functions Cfront
Involves some overhead Virtual table How the language was first compiled
Object of
for class Virt
type Virt Full compiler that produced C as output
class Virt { &Virt::foo
vptr C++ semantics therefore expressible in C
int a, b; &Virt::bar
a
virtual void foo();
b
virtual void bar(); C++ model of computation ultimately the same
};
C++ syntax substantial extension of C
C++ semantics refer to the same model as C
$
C++
I 7 ?
- $ /?* I . $
Equivalent
I 7 $ C implementation
?
- ?* I .
 
I ;9< -9.#" -*,- I ;9< I , 
 ,..,- I .@" So why use C++?
( ( • Specifications are clearer, easier to write and maintain

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Default arguments Declarations may appear anywhere


Another way to simplify function calls Convenient way to avoid uninitialized variables
Especially useful for constructors
I 7 $ ? 
8- $%  $ K 7 % =? ,3* .

void foo(int a, int b = 3, int c = 4) { /* … */ } $
B- $ 2>.+8/7-/.#"
 7 %  $A% ?6  % 2 =96 % - .#"
  +2C>@"
C++ Expands to
78J- $%   C2 $  "   6 % " NN.
foo(3) foo(3,3,4) 0N 2 1  !@"
(
foo(4,5) foo(4,5,4)
foo(4,5,6) foo(4,5,6)

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Multiple Inheritance Multiple Inheritance Ambiguities


Rocket Science What happens with duplicate methods?

Inherit from two or more classes: class Window { void draw(); };


class Border { void draw() };
class Window { … }; class BWindow : public Window, public Border { };
class Border { … };
class BWindow : public Window, public Border { … }; BWindow bw;
bw.draw(); // Error: ambiguous

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

5
Multiple Inheritance Ambiguities Duplicate Base Classes
Ambiguity can be resolved explicitly A class may be inherited more than once

class Window { void draw(); }; class Drawable { … };


class Border { void draw() }; class Window : public Drawable { … };
class BWindow : public Window, public Border {
class Border : public Drawable { … };
void draw() { Window::draw(); }
class BWindow : public Window, public Border { … };
};

BWindow gets two copies of the Drawable base class


BWindow bw;
bw.draw(); // BWindow::draw() calls Window::draw()

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Duplicate Base Classes Implementing Multiple Inheritance


Virtual base classes are inherited at most once A virtual function expects a pointer to its object
struct A { virtual void f(); }
struct B { virtual void f(); }
class Drawable { … }; struct C : A, B { void f(); }
class Window : public virtual Drawable { … }; E.g., C::f() expects “this” to be a C*
class Border : public virtual Drawable { … }; But this could be called with “this” being a B*
class BWindow : public Window, public Border { … };
In-memory

BWindow gets one copy of the Drawable base class   or 


  
representation of a C
A
B
C

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Implementation Using VT Offsets Implementation Using Thunks


 

struct A { int x; virtual void f(); } Create little “helper functions” that adjust
struct B { int y; virtual void f(); virtual void g(); } Advantage: Only pay extra cost for virtual functions
struct C : A, B { int z; void f(); } with multiple inheritance
C’s vtbl
C c; c C’s vtbl

vptr &C::f 0 c
B *b = &c;

&C::f
x B in C’s vtbl vptr

b->f(); // C::f()
vptr &C::f –2 x B in C’s vtbl
y &B::g 0 vptr &C::f_in_B
1. b is a B*: vptr has f(), g() z y &B::g
z
 !"$#&%'( )&* (+,.-
9 /10 )2 / !3$% )* +3465,87
2. Call C::f( this – 2 )
3. First argument now points to a C

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

6
Namespaces Namespaces
 Namespace pollution  Scope for enclosing otherwise global declarations
• Occurs when building large systems from pieces
• Identical globally-visible names clash         
• How many programs have a “print” function?

 !        "
• Very difficult to fix
      %$'&)(+*,-*/.10 2-.43/&.
#
 Classes suggest a solution
 65       %

 
(  (
/  #7  8   69/: 
   
(   
   %;$69<  4>==  >  

 4"== !  ?4.1  
 Two f’s are separate


Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Namespaces Namespaces
'@   1A directive brings namespaces or objects into
 Namespaces are open: declarations can be added
scope

    
        
    
  # %$'&)(+*,-*/.10 23!.&.
  
 ) 
   "  

     "
 ! 
 
        
@   
4 A 4"==   B   

 A   "   // Add Mine::g() to Mine


/ (  
   ?CD6E  ."F // invoke Mine::print
@  
4A:1 4 /% 4  
    
 G- / H$D2 I  (
// Mine::pi

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Namespaces Exceptions
 Declarations and definitions can be separated  A high-level replacement for C’s setjmp/longjmp


          ! @ :L;   '?
 )
   "  
 / ( #7  CD3-+ GLC;  "
(
/J   J 4"= =      D / (   ?CD
I6KDI  +9M
!
 7 C>
  :  4L;     D
!    )1NC    O


Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

7
Standard Template Library C++ IO Facilities
 

I/O Facilities: iostream C’s printing facility is clever but unsafe
   I?     >  A @ 7  %A  A

Garbage-collected String class
   )1N  O   

Containers


• vector, list, queue, stack, map, set
Hard for compiler to typecheck argument types
Numerical against format string

 
• complex, valarray
General algorithms C++ IO overloads the << and >> operators
• search, sort
 . 
  
 
  
@  A 
 Type safe

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

C++ IO Facilities C++ string class


 Printing user-defined types
 Reference-counted for automatic garbage collection

ostream &operator<<(ostream &o, MyType &m) {


string s1, s2;
o << “An Object of MyType”;
return o;
} s1 = “Hello”;

 Input overloads the >> operator


s2 = “There”;
s1 += “ goodbye”;
s1 = “”; // Frees memory occupied by “Hello goodbye”
int read_integer;
cin >> read_integer;
Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

C++ STL Containers Iterators


 Vector  Mechanism for stepping through containers
• Dynamically growing, shrinking array of elements

vector<int> v;
vector<int> v; for ( vector<int>::iterator i = v.begin();
v.push_back(3); // vector can behave as a stack i != v.end() ; i++ ) {
v.push_back(2); int entry = *i;
int j = v[0]; // operator[] defined for vector }

v.begin() v.end()

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

8
Other Containers Associative Containers


Insert/Delete from Keys must be totally ordered
front mid. end random access

Implemented with trees
vector O(n) O(n) O(1) O(1) set
list O(1) O(1) O(1) O(n) • Set of objects
set<int, less<int> > s;
deque O(1) O(n) O(1) O(n)
s.insert(5);


set<int, less<int> >::iterator i = s.find(3);
map
•Associative Array
map<int, char*> m;
m[3] = “example”;

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

C++ in Embedded Systems C++ Features With No Impact


 Dangers of using C++
 Classes
• No or bad compiler for your particular processor • Fancy way to describe functions and structs
• Increased code size • Equivalent to writing object-oriented C code


• Slower program execution

 Much harder language to compile


Single inheritance
• More compact way to write larger structures


• Unoptimized C++ code often much larger, slower than
equivalent C
Function name overloading
• Completely resolved at compile time

 Namespaces
• Completely resolved at compile time
Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

Inexpensive C++ Features Medium-cost Features


 Default arguments  Virtual functions
• Compiler adds code at call site to set default • Extra level of indirection for each virtual function call
arguments • Each object contains an extra pointer


• Long argument lists costly in C and C++ anyway

 Constructors and destructors


References
• Often implemented with pointers
• Function call overhead when an object comes into • Extra level of indirection in accessing data
scope (normal case)
• Can disappear with inline functions
Extra code inserted when object comes into scope


(inlined case)
Inline functions
• Can greatly increase code size for large functions
• Usually speeds execution

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

9
High-cost Features High-cost Features
 Multiple inheritance  Exceptions
• Makes objects much larger (multiple virtual pointers) • Typical implementation:
• Virtual tables larger, more complicated
• Calling virtual functions even slower • When exception is thrown, look up stack until handler


is found and destroy automatic objects on the way

Templates
• Mere presence of exceptions does not slow program
• Compiler generates separate code for each copy
• Often requires extra tables or code to direct clean-up
• Can greatly increase code sizes
• Throwing and exception often very slow
• No performance penalty

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

High-cost Features Bottom-line


 

Much of the standard template library C still generates better code
Uses templates: often generates lots of code


Easy to generate larger C++ executables
• Very dynamic data structures have high memory-
management overhead Harder to generate slower C++ executables
Easy to inadvertently copy large datastructures


Exceptions most worrisome feature


• Consumes space without you asking
• GCC compiler has a flag to enable/disable exception
support –fexceptions and –fno-exceptions

Copyright © 2001 Stephen A. Edwards All rights reserved Copyright © 2001 Stephen A. Edwards All rights reserved

10

You might also like