·
Introduction
o
C++ developed by Bjarne Stroustrup
of AT&T Bell Labs in the early 1980’s.
o
ISO Standard Ratified 1998
o
C++ is like C with Classes and additional features. Using classes, the language supports Object
Oriented Programming (OOP)
o
Classes support the combination of data and algorithms. It is similar to a C structure, only it has
methods and protection levels.
o
OOP allows for encapsulation, inheritance, and polymorphism.
§
Encapsulation – Binding together of all the information, capabilities,
and responsibilities of an entity into a single object. Thus clients of the class can use it without
knowing or caring about how it works.
They only need to know what it does – not how it does it.
// In the example below, _age
may be accessed through
// accessor, mutator and member functions. It may also be
// initialized through the constructor.
class Cat
{
public:
Cat(int age); //
constructor
~Cat(); //
destructor
int getAge()
const; // accessor function
void setAge(int
age); // mutator function
void meow() const; //
member function
private:
int _age; // member variable
};
Note: private members are not available to derived
classes.
// In the example below, the constructor and/or other
// member functions
may be used to set _age, but the public
// has no direct
access to setting the age. They can only
get
// the age. This is due to the fact that setAge()
is private.
class Cat
{
public:
Cat(); //
constructor
~Cat(); //
destructor
int getAge()
const; // accessor function
void meow() const; //
member function
private:
void setAge(int
age); // mutator function
int _age; // member variable
};
// Below, _age is public and anyone can directly set and
// get _age
without use of any member functions. Why
is
// this
bad? It is bad because the user can put
the cat’s age
// at 999 or
any other unreasonable age! The mutator
// function
can be designed to provide limits when setting
// the cat’s
age and send an error message to the user if an
// age that is
out of bounds is entered.
class Cat
{
public:
Cat(); //
constructor
~Cat(); //
destructor
void Meow() const; //
member function
int _age; // member variable
};
§
Inheritance – Writing reusable code

§
Polymorphism – Ability to associate many meanings to one function name
by means of the late-binding mechanism. Thus, polymorphism, late-binding, and
virtual functions are all the same topic.
Beyond the scope of the first class, but discussed in detail later on in
the course.
o
C++ allows overloading of functions and operators
§
Function Overloading – function has the same name but is implemented
according to the arguments passed.
// Prototypes (declarations) for a function overloading
void f();
void f(int);
void f(char, int,
char*);
// The corresponding
functions may be called as follows
f();
f(5);
f(‘B’, 8, “Hello”);
§
Operator Overloading – allows us to overload operators for manipulation
of objects.
ObjectA = ObjectB;
ObjectC = ObjectA
+ ObjectB;
o
C++ template facility allows for algorithm abstraction
§
C++ templates allow coding in which one or more types are parameterized
o
C++ uses namespaces and allows for multiple namespaces that may be helpful
for reusing function and class names.
o
C++ has exception handling
o
Memory management is much like C Programming, i.e., you are responsible
for allocating and freeing memory as appropriate
·
Commenting
o
You should comment function description headers, ambiguous variable
names, and parts of code that are not easily understood by another programmer
§
Function Description Header
////////////////////////////////////////////////////////////////////////////////
// calculateInterest()
//
// Description: This
function will return the interest
// on a loan or investment for a given period of time.
//
// Inputs: principalAmount
// numberMonths
//
// Outputs: none
//
// Return: interest
/////////////////////////////////////////////////////////////////////////////////
§
Ambiguous Variable Names
float principalAmount;
int i, j, k; //
Counter Variables
§
Parts of Code Not Easily Understood
// Set status LED color to
green
*pLedRegister
&= ~0x30;
*pLedRegister
|= 0x20;
·
White Space
o
Make good use of white space for program clarity. Separate logical blocks of code with white
space.
o
Do not have multiple program statements on the same line.
·
First C++ Example
#include <iostream>
using namespace std;
int main()
{
cout << "Hello
world!" << endl;
return 0;
}
·
Variables, Expressions and Assignment Statements
o
Variables
§
Must begin with a letter or underscore.
Characters after that must be a letter, number, or underscore.
§
Variable names are case-sensitive.
They are typically written with the first letter lower-cased and word
boundaries in upper-case. For
example: costOfProduction
§
The variable name identifier cannot be a
C++ keyword or reserved word (e.g., int).
§
Variables must be declared before they are used. An example that declares an integer totalDistance is shown below (in the example, the variable
is initialized to 50):
int totalDistance
= 50;
or
int totalDistance(50);
Both declarations accomplish the same result of
declaring the integer totalDistance and assigning a
value of 50 in the declaration.
If a variable is declared without an initial value,
the variable has a garbage value in it that consists of the combination of ones
and zeros that was left in its memory location by the last program that used
that particular portion of memory
o
Declared Constant
§
You can initialize a variable that cannot be changed in the
program. If an attempt to change the
variable is made, the compiler will produce an error condition. Example:
const int
FEET_PER_MILE = 5280;
const double PI = 3.14159;
o
Expressions
§
Arithmetic expressions follow the order of precedence in Appendix II of
the assigned book. However, it is best
for force precedence using parenthesis for easy readability.
double celsius
= 32;
double fahrenheit;
fahrenheit = (9./5) * celsius + 32;
o
Type Cast
§
A type cast allows you to change a variable of one type to another
type. For now, we will only concern
ourselves with static_cast. This can be thought of as something like a
function that takes an argument and returns an equivalent value argument of the
type cast. Example:
int number1 = 3, number2 = 4;
double number3;
number3 = static_cast<double>(number1) / number2;
Note: Don’t be fooled as shown below.
// Compiler Error ... need parenthesis around
number1.
number3 = static_cast<double>number1
/ number2;
// Here, the result of number3 is that of an
// integer division.
number3 = static_cast<double>(number1 / number2);
§
Other Casts
·
const_cast<Type>(Expression) – cast away constantness
·
dynamic_cast<Type>(Expression) – Used for safe downcasting from one type to a descendent type in an
inheritance hierarchy
·
Older way of doing C++ casts:
o
int(9.3) – returns a cast to int
value of 9
o
(int)9.3 – returns a cast to int value of 9
o
Increment and Decrement Operators
§
Increment Operator
++counter; // pre-increment
counter++; // post-increment
§
Decrement Operator
--counter; // pre-increment
counter--; // post-increment
o
Console Input/Output
§
Performed using the cin, cout
and cerr objects
·
cout and cerr
send output stream to the monitor. The
object cout uses the standard output stream and cerr uses the standard err output
stream. Output can go to different files
if system file redirection is imposed.
§
<< is called the Insertion Operator
§
>> is called the Extraction Operator
cout << “Enter your
name: ”;
cin >> name;
cout << “My name is ”
<< name << endl;
·
Flow Control
o
C++ Handles Flow Control using branching and looping statements as is
done in the C Language
o
Relevant Operators in Order of Precedence
|
Operator |
Meaning |
|
! |
Not |
|
> < <= >= |
Greater
Than Less
Than Less
Than or Equal Greater
Than or Equal |
|
= = != |
Is
Equal To Is
Not Equal To |
|
&& |
Logical
AND |
|
|| |
Logical
OR |
o
if Statement
if((x >=0) && (x
< 10))
cout << “X is between 0 and
9\n”;
o
if-else Statement
if((x >=0) && (x
< 10))
cout << “X is between 0 and
9\n”;
else
{
cout << “X is not between 0
and 9\n”;
x = 0;
cout << “X has been set to
0\n”;
}
o
switch Statement (used in place of long if-else constructs)
switch(someNumber)
{
case 0:
cout << “The number is
zero\n”;
break;
case 1:
case 2:
cout << “The number is one
or two\n”;
break;
case 10:
cout << “The number is
ten\n”;
break;
default:
cout
<< “The number is not zero, one, two,
or ten\n”;
}
o
enum Keyword – treated as an integer
// Example
enum RETURN_MSGS { SUCCESS,
GENERAL_FAILURE,
MEMORY_ALLOCATION,
CANNOT_OPEN_FILE,
OUT_OF_BOUNDS,
BAD_INPUT,
DIVIDE_BY_ZERO
};
if(daysWorkedDuringWeek > 7)
return OUT_OF_BOUNDS;
// Example
enum RETURN_MSGS result;
...
switch(result)
{
case SUCCESS:
break;
case GENERAL_FAILURE:
cout << “General Failure
Encountered\n”;
break;
etc...
}
o
Conditional Operator
(Evaluate a Condition) ? condition true : condition false
// Example
(a > b) ? c = a : c = b; // c equals the
max of a and b
// Example
#define MAX(a,b) (a > b) ? a : b
c = MAX(a,b);
o
while Statement – loop a block of code while a condition
is true.
while(x > 0)
{
cout << “X = ” << x
<< endl;
x--;
}
o
do-while Statement – do a block of code while a
condition is true.
do
{
cout << “X = ” << x
<< endl;
x--;
} while(x > 0);
o
for Statement – loop a specified number of times
for(counter = 0; counter <
10; counter++)
cout << “Counter = ”
<< counter << endl;
o
break and continue Statements
§
break Statement – ends the nearest enclosing switch statement or loop
statement
§
continue Statement – ends the current loop body iteration of the
nearest enclosing loop statement