Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 1 -
C to C++C to C++
C++ Comments
Can use the symbol //
To identify single line comments
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 2 -
C to C++C to C++
const SpecifierUsed to declare or specify a constant
const int speed = 60;
Transforms
Symbolic Variable
…. speed ….
Symbolic constant
…. speed ….
Within the scope of speed
speed = 85; // Illegal
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 3 -
C to C++C to C++
Const and Pointers
Object Pointer
*
ptr = “Hello”;
const ptr = “Hello”;
ptr = “Hello”;
char
const ptr = “Hello”;
char
const char
const char
*
*
*
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 4 -
C to C++C to C++
Declarations within BlocksCan declare variables within block after code segment
void main ()
{
int a;
….
code
int b;
more code (using b)
char* c;
yet more code (using c)
}
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 5 -
C to C++C to C++
Declarations within a Loopfor (int i = 0; i < 10; i++) {
for (int i = 2; i < 15; i++) {
for (int i = 4; i < 25; i++){…}// i from inner loop
}}i from outer loop…for (int i = 0; i >20; i--){}
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 6 -
C to C++C to C++
Functionsprototypes
void myDataDisplay( int, char*, float)
Parameter names are not necessary
Good style suggests using names
void myDataDisplay( int range, char* label, float value)
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 7 -
C to C++C to C++
Default Parameters
Trailing set or args is Initialized to Default Values
The Default Values are Specified in Prototype…..
void myFunction (int earth, int moon = 10, int stars = 20);
Can call the function with fewer args than the declared….
printThings (10);
printThings(10,20);
printThings (10, 20, 30);
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 8 -
C to C++C to C++
Overloading Function Names - Simple Polymorphism
Functions can use the same names within the same scopeIf ……….
Each function declaration and use can be distinguished by
Name and Signature
Signature
Number and type of parameters
char *s = "This is a string";printThings (10); // Print an intprintThings('a'); // Print a charprintThings (s); // Print a string
char *s = "This is a string";printThings (10); // Print an intprintThings('a'); // Print a charprintThings (s); // Print a string
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 9 -
C to C++C to C++
Overloading Function Names - Simple PolymorphismRedeclaration
If return type and signatures match…the arg names are irrelevant
extern void print (int a, int b);
void print (int c, int d);
Erroneous Redeclaration
If signatures match and return types differ
char print (int a, int b);
void print (int c, int d);
Overloaded
If signatures differ in the
Number, Type, or Order of args
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 10 -
C to C++C to C++
Reference Types - Definition
Serve as alias for an object
Must be initialized like a const
syntax
& operator following the type specifier in the declaration
int aValue = 20; // declare and define a value
int &speed = aValue;// declare and initialize a reference
speed += 10; // adds 10 to aValue
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 11 -
C to C++C to C++
Reference Types - Initialization
A reference of type T
Must be initialized by
Object of type T
Object that can be converted to a type T
Cannot be changed to refer to another object after initialization
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 12 -
C to C++C to C++
Reference Types - Initializationnon const
Initialized only by an lvalue of the exact type
Reference refers to initializer
const
Initialized only by an
rvalue
lvalue
Does not need to be of the exact type
Temporary object of type T created
Initialized with the initializer
Reference refers to the temporary
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 13 -
C to C++C to C++
Reference Types - Initialization
unsigned char mine;int d1, d2;
int &a = 1024; // illegal 1024 is not an lvaluechar &b = mine; // illegal not exact typeint &c = d1 + d2; // illegal not an l value
const int &a = 1024; // okconst char &b = mine; // okconst int &c = d1 + d2; // ok
unsigned char mine;int d1, d2;
int &a = 1024; // illegal 1024 is not an lvaluechar &b = mine; // illegal not exact typeint &c = d1 + d2; // illegal not an l value
const int &a = 1024; // okconst char &b = mine; // okconst int &c = d1 + d2; // ok
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 14 -
C to C++C to C++
Reference Types - Initialization
Initialization can be eliminated only in
Argument declaration
Declaration of a function return type
Declaration of a class member
Extern specifier used
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 15 -
C to C++C to C++
References vs. Pointers
References do not support pointer like operations
Cannot have …….
Pointers to references
Arrays of references
Consequence of first
int & v[ ] v[1] *(v+1)
Reference to reference
Reference to bit fields
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 16 -
C to C++C to C++
void increment (int* &i) {i++;}
int main( ){
int* iPtr = 0;
cout << "iPtr = " << iPtr << endl; // Prints 0x00000000
increment (iPtr);
cout << "iPtr = " << iPtr << endl; // Prints 0x00000002
return 0;}
void increment (int* &i) {i++;}
int main( ){
int* iPtr = 0;
cout << "iPtr = " << iPtr << endl; // Prints 0x00000000
increment (iPtr);
cout << "iPtr = " << iPtr << endl; // Prints 0x00000002
return 0;}
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 17 -
C to C++C to C++
References as ParametersPass by Value
Function never accesses the actual args
Manipulates a local copy stored on the stack
Changes made to the local copies
Do not affect the actual args
Pass by Reference
Function accesses the actual args
Address of the arg is passed
If arg is not to be changed use const
myFunction (const int &x)
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 18 -
C to C++C to C++
new and delete operators
To manage allocation and deallocation of memory at runtime
C has the functions
malloc
free
C++ introduces the operators
new
delete
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 19 -
C to C++C to C++
new and delete operators
new operator
Gives programmer control over storage allocation from heap
at runtime
Similar to malloc
delete operator
Gives programmer control over storage deallocation at runtime
Similar to free
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 20 -
C to C++C to C++
new and delete operatorsnew Operator
syntax
new (nothrow) type [amount]
returns
On success
pointer to newly allocated memory
On failure
Exception or NULL
new type ( value )
Initializes the variable to value
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 21 -
C to C++C to C++
new and delete operators
int *myPtr = new int;Allocate sufficient storage to hold a single integerPointer to storage assigned to myPtr
int * myPtr = new char [ strlen (“Bon jour mes amis”) + strlen (“touts les jour”) ];Returns a pointer to an area of memory to hold 17 + 14 characters
new int(23);Returns a pointer to an int initialized to 23
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 22 -
C to C++C to C++
new and delete operatorsdelete operator
“Destroys” object created by new…returns the memory to heap
No arguments
Return type void
syntax
delete expression
delete [ ] expression
In both cases expression pointer to memory allocated by new
Do not use delete to free an array
This operation is undefined
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 23 -
C to C++C to C++
new and delete operatorsDont’s
• Do not use delete to free an array
• Delete a single object with delete [ ]
• Apply delete operator to object not created by new
• Try to access a deleted object
• Try to delete a pointer to a const - that’s changing it
Deuze
• Use delete [ ] to free any objects created with new [ ]
• Use delete to free any objects created with new or new ( )
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 24 -
C to C++C to C++
int main( ){
char *stuff[ ] = {" is ", "getting ", "longer "};char *s = new char [strlen ("My string") +1];strcpy (s, "My string");for (int i = 0; i< 3; i++){ s = growString(s, stuff[i]); cout << s << endl;}return 0;
}
char *growString(char *myString, char *aString){
char *tString = new char [strlen(myString) + strlen(aString) + 1];strcpy (tString, myString);strcat (tString, aString);delete[ ] myString;
return tString;}
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 25 -
C to C++C to C++
Enumeration Types
The name of an enumeration is a type name
One can declare an instance of type Tenum Bool {FALSE, TRUE};
It is not necessary to use enum qualifier in front of the type name
enum Bool {NO, YES}; // NO = 0, YES = 1enum Bool {NO, FALSE=0, YEP, TRUE=1, MAYBE}; // 00112enum Bool {FALSE, TRUE}; // 01
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 26 -
C to C++C to C++
Enumeration Types
enum Bool {FALSE, TRUE};
main(){
Bool found = FALSEcode
if ( TRUE == found ){
…}
}
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 27 -
C to C++C to C++
Scope Operator
The scope operator is given by the symbol
:: Operator
Used to resolve name conflicts
Access global variables
:: DOES NOT access up one level
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 28 -
C to C++C to C++
Inline Specifier
Directs the compiler to perform inline substitution of function
…… Similar to a macro
This is only a recommendation and may be only partially implemented
struct Array{
….void put (int aValue);
….};
inline void Array::put(int aValue){
….}
inline int min (int v1, int v2){
return (v1 <= v2 ? v1 : v2)}
then…
int minVal = min(I,I);
becomes
int minVal = (v1 <= v2) ? v1 : v2;
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 29 -
C to C++C to C++
Input and Output
Input and OutputSimilar to C…. These are not defined within the C++ language
I/O is provided as component of C++ Standard Library
Input or Output Data interpreted as stream of bytes
To use I/O functions … we must include <iostream>
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 30 -
C to C++C to C++
Input and Output
IO Stream OperationsSupported by
input stream …… istream, ifstream, istrstreamoutput stream …. ostream, ofstream, ostrstream
IOstream classDerived from
istreamostream
IOS
OStreamIStream
IOStream
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 31 -
C to C++C to C++
Input and Output
OStreamOutput operation … InsertionSignified by insertion operator <<
Value inserted into (output) stream
IStreamInput operation … ExtractionSignified by extraction operator >>
Value extracted from (input) stream
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 32 -
C to C++C to C++
Input and Output
Predefined Stream Objects cin
istream class object connected to standard input cout
ostream class object connected to standard output cerr
ostream class object connected to standard errorProvides unbuffered output
clogostream class object connected to standard error
Provides buffered output
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 33 -
C to C++C to C++
Input and Output
Outputcout << stuff;
Inputcin >> place to put stuff;
Can accept Any builtin data types Any complex expression that evaluates to a data type Can be overloaded to accept user defined types cin does not allocate space for stuff
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 34 -
C to C++C to C++
Output Formatting
Must include <iomanip>
PrecisionOne can alter the precision of the output
precision( )No argument returns current precision
cout.precision( );
With an argument sets the precisioncout.precision( int aPrecision );
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 35 -
C to C++C to C++
Output Formattingput (char c)
Output
Single character
cout.put(‘a’);
write (char *s, int n)
Output
n characters from string *s
char *s = “my name is”;
cout.write(s, 5)
gives my na
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 36 -
C to C++C to C++
Output Formatting
Change of baseUse manipulators
oct, dec, hex, scientific, fixed, setprecision(int n)
cout << hex;Change output base to hexcout << hex << 256
prints 100
Change will remain in effect until changed again
Copyright 2008 Oxford Consulting, Ltd 1 October 2008
- 37 -
C to C++C to C++
Input Formatting
get (char c)Input single character
char a;cin.get(&a); // Enter an ‘f’cout << a; // Prints an ‘f’
read (char *s, int n)Input n bytes from stdin into memory beginning at *s
getline (char *s, int n)Input upto n characters from stdin into memory beginning at *sInsert a NULL into the buffer