Professional Documents
Culture Documents
C++ warm-up
History of C++
1972: C language developed at Bell Labs
Dennis Ritchie wrote C for Unix OS
Needed C for work with Unix
Versions of C++
ANSI C++
Microsoft C++ (MS Visual C++ 6.0)
Other vendors: Borland, Symantec, Turbo,
Many older versions (almost annual) including
different version of C too
Many vendor specific versions
Many platform specific versions
For this class: Unix / Linux based versions
g++
Characteristics of C++ as a
Computer Language
Procedural
Object Oriented
Extensible
...
Other OO Languages
Smalltalk
pure OO language developed at PARC
Java
built on C/C++
objects and data types
Disadvantages of C++
Tends to be one of the less portable languages
Complicated?
40 operators, intricate precedence, pointers, etc.
can control everything
many exceptions and special cases
tremendous libraries both standard, vendor specific,
and available for purchase, but all are intricate
Advantages of C++
Available on most machines
Can get good performance
Can get small size
Can manage memory effectively
Can control everything
Good supply of programmers
Suitable for almost any type of program (from
systems programs to applications)
Primitive Types
bool
true or false (only C++)
char
8/16-bit
short
16-bit signed integer
int 32-bit signed integer
unsigned 32-bit unsigned integer
long
32 / 64-bit signed integer
float
32-bit floating point
double 64-bit floating point
Precedence Example
What is: 5 + 21 / 4 % 3
= 5 + (21 / 4) % 3
= 5 + ( 5 % 3)
=5+2
=7
Explicit Casting
(type) expression
Possible among all integer and float types
Possible among some class references
E.g. int i = (int) ( (double)5 / (double)3 )
Implicit Casting
Applied automatically provided there is no
loss of precision
float double
int double
Example
int iresult, i=3;
double dresult, d=3.2;
dresult = i/d => implicit casting dresult=0.9375
iresult = i/d => error! Why? Loss in precision,
needs explicit casting
Control Flow
if (boolean)
statement;
else if(boolean)
statement2;
else
statement3;
Booleans only, not integers!
if (i > 0) correct
if (i = 2) correct / incorrect ?
Switch / case
switch (controlVar)
{
case 'a' :
statement-1
break;
case 'b' :
statement-2
break;
default :
statement-3
break;
}
Loops
while(<boolean>)
statement;
do
statement;
while(<boolean>)
Loop Refresher
Which loops must execute their statements at
least once?
Which loops can choose to never execute their
statements?
Which value of the boolean indicates to do the
statements again?
Overview
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Passing Parameters
C++ allows for three different ways of passing parameters:
Pass by value
E.g. foo (int n)
Appropriate for small objects (usually primitive types) that should not
be altered by the function call
Pass by reference
E.g. foo(bool & errFlag)
Appropriate for small objects that can be altered by the function call
Array types are always passed by reference
Passing by value
void square(int i)
{
i = i*i;
}
int main()
{
int i = 5;
square(i);
cout << i << endl;
}
Passing by reference
void square(int& i)
{
i = i*i;
}
int main()
{
int i = 5;
square(i);
cout << i << endl;
}
What is a reference?
An alias another name for an object.
int x = 5;
int &y = x; // y is a
// reference to x
y = 10;
What happened to x?
What happened to y? y is x.
Pointer
int a = 10;
int b = 20;
int &c = a;
c = b;
int a = 10;
int b = 20;
int *c = &a;
c = &b;
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Classes
Provide a mechanism for defining classes of
objects.
We can define the class of all computers to have
certain characteristics.
An instance of a computer is your home PC.
Classes in C++:
Why Create Classes / Objects?
Keeps all related info (i.e., data) together
Refer to all the related info by one name
Protect the information
Hide methods that use or change the info
Keep methods together with their related info
Mammals
inherits
class
Tigers
Humans
instance-of
Hank
inherits
Peggy
class
instance-of
Tony
Function Definitions
void human::setHeight(int heightValue)
{
if (heightValue > 0)
height = heightValue;
else
height = 0;
}
int human::getHeight()
{
return(height);
}
Example
// first we define the variables.
int height = 72;
int result = 0;
human hank;
//set our humans height
hank.setHeight(height);
//get his height
result = hank.getHeight();
cout << Hank is = << result <<
inches tall << endl;
Output
Hank is 72 inches tall
Instantiating an Object
The class definition does not create any objects
Instantiating and constructing are equivalent words for
building a new object based on the model (i.e., template) of the
class
Instantiating is done just like declaring a variable of a built in
data type
Instantiating is done by a constructor (sometimes called a
constructor method)
If the "class provider" does not provide a constructor, then the C++
compiler provides a default one automatically
The default constructor does not provide values to the data members (i.e.
the instance variables)
Referencing an Object
Each object has a name (or a location) which
is assigned when the object is instantiated
private data members are accessible only
within the class
since most data members are private, that means
that these data items are accessed generally by
means of member functions
myElephant.age = 72; //won't work, assuming age
//is declared as private
myElephant.setAge(72); // will work
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Inheritance
The power of object-oriented languages
Enables reuse of fields/methods
All parent fields included in child instantiation
Protected and public fields and methods directly
accessible to child
Parent methods may be overridden
New fields and methods may be added to the child
Multiple inheritance
Inheritance (contd)
class classname: public parentname {
private:
.;
public:
.;
//access to parent methods through
// parentname::methodname
}
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Header file
For complex classes, the member functions
are declared in a header file and the member
functions are implemented in a separate file.
This allows people to look at the class definitions,
and their member functions separately
#include
#include Segment.H
#include <iostream>
Header Guards
#ifndef __SEGMENT_HEADER__
#define __SEGMENT_HEADER__
// contents of Segment.H
//...
#endif
To ensure it is safe to include a file more than once.
Header Guards
#ifndef __SEGMENT_HEADER__
#define __SEGMENT_HEADER__
// contents of segment.H If this variable is
Define it. not defined
//...
#endif
To ensure it is safe to include a file more than once.
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Output
#include<iostream>
Tell compiler that we are doing I/O
cout
Object to which we can send data.
<<
operator for sending data.
endl `\n `\t
Special symbols that we can send.
Formatting Output
cout.setf(long flag)
Set different formatting
parameters for next output.
ios::left
ios::right
ios::scientific
ios::hex
ios::dec
ios::uppercase
cout.unsetf(long flag)
Disable these formatting
parameters.
Example
#include<iostream.h>
main()
{
cout.width(10); //sets width to 10
cout << hello << endl;
cout.setf(ios::left);
cout << hello << endl;
cout << 16 << endl;
cout.setf(ios::hex, ios::basefield);
cout << 16 << endl;
}
Output
hello
hello
16
10
Input
#include <iostream.h>
Tell the linker we are doing basic I/O
cin
The input object. It retrieves input from the keyboard
>>
The extractor operator.
Example
#include <iostream.h>
main ()
{
int userInput;
cout << Enter number:;
cin >> userInput;
cout << You entered <<
userInput << endl;
}
Output
Enter number:12345
You entered 12345
#include <string>
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
// Check input
if(argc<2)
{
cout<<"Usage: "<<argv[0]<<" <filename>"<<endl;
return 0;
}
// Try to read from file
cout<<"Reading tokens from file '"<<argv[1]<<"':"<<endl;
ifstream in(argv[1]);
if(!in)
cout<<" - Could not read from file '"<<argv[1]<<"'."<<endl;
else
{
string token;
cout.setf(ios::right);
for(unsigned i=1; in>>token; i++)
cout<<setw(4)<<i<<": "<<token<<endl;
}
in.close();
cout<<endl;
// Allow user to enter a token
string text;
cout<<"Enter some text: ";
getline(cin, text);
// Append new tokens to file
ofstream out(argv[1], ios::app);
if(out)
out<<endl<<text<<endl;
else
cout<<"- Could not write to file '"<<argv[1]<<"'"<<endl;
out.close();
return 0;
}
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
What is a pointer?
int x = 10;
int *p;
p = &x;
10
What is a pointer?
int x = 10;
int *p;
p = &x;
*p = 20;
*p is the value at the address p.
20
What is a pointer?
int x = 10;
int *p;
p = &x;
Declares a pointer
to an integer
& is address operator
gets address of x
*p = 20;
* dereference operator
gets value at p
A Pointer Example
int main(){
int i, j;
int *pi, *pj;
i
j
pi
pj
*pj
cout
cout
cout
cout
=
=
=
=
=
5;
i;
&i;
pi;
4;
<<
<<
<<
<<
i <<
j <<
*pi <<
*pj <<
return 0;
}
> 4, 5, 4, 4
;
;
;
endl;
Problems
Dangling pointers
Pointers to memory that has already been
deallocated
segmentation fault (core dump)... or worse....
Memory leak
Loosing pointers to dynamically allocated memory
Substantial problem in many commercial products
See Windows 98
int* badFunction(){
int num = 10;
return #
}
int* stillBad(int n){
n += 12;
return &n;
}
int main(){
int num = 12;
int *myNum = badFunction();
int *myOtherNum =
stillBad(num);
cout << *myNum << , ;
cout << *myOtherNum << endl;
return 0;
}
return 0;
}
int evilFunction(){
int *i = new int(9);
return *i;
}
int main(){
int num = evilFunction();
return 0;
// Im loosing my memory!!
}
return 0;
}
// ok
// ok
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Class Destructors
If a class dynamically
allocates memory, we
need a way to deallocate
it when its destroyed.
Distructors called upon
distruction of an object
class MyClass{
public:
MyClass(){
// Constructor
}
~MyClass(){
// Destructor
}
...
};
Destructors
delete calls the objects destructor.
delete frees space occupied by the object.
A destructor cleans up after the object.
Releases resources such as memory.
Destructors an Example
class Segment
{
public:
Segment();
virtual ~Segment();
private:
Point *m_p0, *m_p1;
};
Destructors an Example
Segment::Segment()
{
m_p0 = new Point(0, 0);
m_p1 = new Point(1, 1);
}
Segment::~Segment()
{
delete m_p0;
delete m_p1;
}
Assignment Operator:
class Rooster{
public:
...
Rooster&
operator=(const Rooster &rhs){
// Copy stuff
}
...
};
...
// Usage
Rooster r(12), s(10);
r = s;
Canonical Form
All classes should have
each of the following:
Default constructor
Copy constructor
Assignment operator
Destructor
// Canonical Cow
class Cow{
public:
Cow(){...}
Cow(const Cow &rhs){...}
Cow& operator=(const Cow &c)
{...}
~Cow(){...}
...
};
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructore, copy constructor, and assignment
operator
Const
Template
Introducing: const
void Math::printSquare(const int& i)
{
Wont compile.
i = i*i;
cout << i << endl;
}
int main()
{
int i = 5;
Math::printSquare(i);
Math::printCube(i);
}
Namespaces
Namespaces are kind of like packages in Java
Reduces naming conflicts
Most standards C++ routines and classes and
under the std namespace
using namespace
#include <iostream>
...
std::string question =
How do I prevent RSI?;
std::cout << question << std::endl;
using namespace std;
string answer = Type less.;
cout << answer << endl;
But, not in header files!
Outline
History and overview
Basic features
Parameter passing
Classes
Inheritance and virtual
Header file
IO
Memory Management
Big three: destructor, copy constructor, and assignment
operator
Const
Template
Template
What exactly are templates for, and why learn them?
Limited Generic Programming (polymorphism)
Some functions have the same semantic meaning for some (if not all) data
types. For instance, a function print() should display a sensible
representation of anything passed in. Ideally, it shouldnt need to be
rewritten for each possible type.
Example:
a swap function
variables. This functions behavior is similar for all data types. Templated
functions let you do that in most cases without any syntax changes.
Template Syntax:
swap dissected
Template Syntax:
Using it
Syntax
Example:
double d1 = 4.5, d2 = 6.7;
swap(d1, d2);
Class Templates:
Example
File: Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
template <typename T>
class Matrix {
public:
Matrix(int rows, int cols);
Matrix(const Matrix &other);
virtual ~Matrix();
Matrix& operator=(const Matrix &rhs);
T* operator[](int i);
int getRows() const;
int getCols() const;
protected:
void copy(const Matrix &other);
private:
Matrix();
int m_rows;
int m_cols;
T *m_linArray;
};
#endif /* MATRIX_H */
Class Templates:
Example contd
#include "Matrix.h"
template <typename T>
Matrix<T>::Matrix()
{}
template <typename T>
Matrix<T>::Matrix(int rows, int cols) {
m_rows = rows;
m_cols = cols;
m_linArray = new T[m_rows * m_cols];
}
return *this;
File: Matrix.cc
Class Templates:
return *this;
specialization region of
Notice that the
Matrix<T>::
specialization
region does not include the
return type. Thus the return
type needs explicit
specialization
This may be
obvious, but
remember that
though constructors
and destructors
have the same name
as a the class
template, they are
functions and do not
need to be
specialized.
Class Templates:
usage
Syntax
Templated classes must be explicitly specialized. Thus, to create a 2
dimensional Matrix of doubles using the last example, the syntax would be:
Matrix<double> m(3,3);
STL
Allows you to easily store anything without
writing a container yourself
Will give you the most hideous compile errors
ever if you use them incorrectly.
STL example
using namespace std;
typedef list<int> intlist;
typedef intlist::iterator intlistIter;
intlist v;
v.push_back(4);
intlistIter a;
for(a = v.begin(); a != v.end(); ++a)
{
int c = (*a);
}
Compilation Model
Preprocessor
Resolves all preprocessor directives
#include, #define macros, #ifdef, etc.
Compiler
Converts text into object files
May have unresolved interobject references
Linker
Resolves all interobject references (or gives you a linker error)
Creates the binary executable
Loader
Loads the program into RAM and runs the main() function
Compilation
Compiler
Preprocessor
Object files
Executable
Linker
Associates functions with definitions
HelloWorld.cpp
#include <iostream> // For cout
using namespace std;
int main(){
cout << "Hello World!" << endl;
return 0;
}
makefile
> make
Simple makefile
All: hello
hello: hello.o
g++ -o hello hello.o
hello.o: hello.cpp
g++ -c hello.cpp
ix$ ls
hello.cpp makefile
ix$ make
g++ -c hello.cpp
g++ -o hello hello.o
ix$ ls
hello* hello.cpp hello.o makefile
ix$ ./hello
Hello World!