C
C
Outline
C++ basic features
Programming paradigm and statement syntax
Class definitions
Data members, methods, constructor, destructor
Pointers, arrays, and strings
Parameter passing in functions
Templates
Friend
Operator overloading
I/O streams
An example on file copy
Makefile
2
Memory
store its local variables.
Collectively, this storage is called location
the stack
This storage (memory aka RAM),
is a series of storage spaces and
their numerical addresses
Instead of using raw addresses,
we use variables to attach a name
to an address
All of the data/variables for a
particular function call are located
void
{
in a stack frame
i
d2
d1
y
x
aFunc(int x, int y)
d1
aFunc
x
x
main
4
other
7
Basic C++
Inherit all C syntax
Class Definitions
A C++ class consists of data members and methods (member
functions).
Initializer list: used to initialize the data
class IntCell
Avoid implicit type conversion
members directly.
{
public:
explicit IntCell( int initialValue = 0 )
: storedValue( initialValue ) {}
int read( ) const
{ return storedValue;}
void write( int x )
{ storedValue = x; }
private:
int storedValue;
Member functions
Indicates that the members invocation does
not change any of the data members.
Data member(s)
10
11
Constructors
A constructor is a special method that describes how an
12
Destructor
A destructor is called when an object is deleted either
13
Pointers
A pointer is a variable which
x
(4104)
y
(4100)
4096
n
(4096)
14
A Pointer Example
Box diagram
Memory Layout
The code
void doubleIt(int x,
int * p)
{
*p = 2 * x;
}
int main(int argc, const
char * argv[])
{
int a = 16;
doubleIt(9, &a);
return 0;
}
a gets 18
main
16
p
(8200)
8192
doubleIt
doubleIt
x
x
(8196)
a
(8192)
16
main
p
15
16
class IntCell
{ }
{
public:
explicit IntCell( int
initialValue = 0 );
void IntCell::write( )
{ storedValue = x; }
int storedValue;
}
IntCell.h
IntCell.cpp
The interface is typically placed in a file that ends with .h. The
member functions are defined as:
ReturnType FunctionName(parameterList);
The implementation file typically ends with .cpp, .cc, or .C. The
member functions are defined as follows:
ReturnType ClassName::FunctionName(parameterList)
{ }
Scoping operator
17
Declaration
IntCell * p; //defines a pointer to an object of class
IntCell
18
Dereferencing Pointers
8888
8888
19
Using a pointer
We can get the value of the object pointed at by a pointer
either by using operator *, or by using operator ->
IntCell a;
int b;
20
Array Declaration
An array is a collection of objects with same type stored
consecutively in memory
Declaring an array
IntCell arr[10]; //an array consisting of 10 IntCell
objects
arr
10 11 12 13 14 15 16
17 18 19
21
Strings
Built-in C-style strings are implemented as an array of
characters.
Each string ends with the special null-terminator \0.
strcpy: used to copy strings
strcmp: used to compare strings
strlen: used to determine the length of strings
Individual characters can be accessed by the array
indexing operator
10 11 12 13 14 15 16 17 18 19
char s[]=abcdefg;
strcpy(s1, s);
//copy s to s1
//(s1 must have enough size)
//including \0
f o o
s1
f o o
\0
s2
50 51 52 53 54 55 56
a b c d e
\0
57 58 59
\0
10 11 12 13 14 15 16
17 18 19
\0
\0 l
50 51 52 53 54 55 56
57 58 59
a b c d e
s1
a b c d e
f
f
\0
22
Output: Value of x = 5
Value of v = 5
When a variable v is passed by value to a
function f, its value is copied to the
corresponding variable x in f
Any changes to the value of x does NOT affect
the value of v
Call by value is the default mechanism for
parameter passing in C++
23
Output: Value of x = 5
Value of v = 4
When a variable v is passed by reference to a
parameter x of function f, v and the
corresponding parameter x refer to the same
variable
Any changes to the value of x DOES affect the
value of v
24
25
26
Reference Variables
27
*
m
&
&
p;
= 10;
j = m; //valid
k; //compilation error
28
References (Summary)
References are an additional name to an
existing memory location
If we wanted something called ref to refer to a variable x:
Pointer:
x
Reference:
9
x
ref
ref
29
30
31
C++ - Template
Template is a generic types
template <class T, int size>
class Stack {
T _store[size];
public:
...
};
Stack<int,128> mystack;
independent algorithms
32
Template Details
Function templates
Return by reference
int & foo(int &b){
return b;
}
main(){
int j;
int a = 5;
main(){
int j;
int a = 5;
j=foo(a); //j is 5
j=3; // a is still 5
j=foo(a); //j is 5
j=3; // a is still 5
foo(a)= 10;
// invalid
34
35
A C++ Example
point.h
class Point {
private:
int _x, _y;
// point coordinates
public:
// begin interface section
void setX(const int val);
void setY(const int val);
int getX() { return _x; }
int getY() { return _y; }
};
Point apoint;
36
37
Main program
main.cc, main.cpp
int main(int argc, char* argv[]) {
Point apoint;
apoint.setX(1);
apoint.setY(1);
// Initialization
//
// x is needed from here, hence, we define it
here and
// initialize it to the x-coordinate of apoint
//
int x = apoint.getX();
}
38
val);
val);
_x; }
_y; }
};
39
: _x(x), _y(y) {
40
41
Operator Overloading
The overloaded operator may not be a member of a class: It can
Friend
We can define functions or classes to be friends of a
character streams
>> input operator (extractor)
<< output operator (inserter)
44
character
45
CountChars.cpp
Program Output
Enter a line or press CTRL-Z: This is the first line.
This is the first line.
Number of characters in line 1 is 23
Enter a line or press CTRL-Z: This is the second
line.
This is the second line.
Number of characters in line 2 is 24
Enter a line or press CTRL-Z:
<CTRL-Z>
Number of lines processed is 2
Total number of characters is 47
46
CountChars.cpp (Header)
// File: CountChars.cpp
// Counts the number of characters and lines in
// a file
#include <iostream>
#include <string>
using namespace std;
#define ENDFILE "CTRL-Z
//ENDFILE is a string
47
CountChars.cpp (Setup)
int main()
{
const char NWLN = '\n'; // newline character
char next;
int charCount;
int totalChars;
int lineCount;
lineCount = 0;
totalChars = 0;
cout << "Enter a line or press "
<< ENDFILE << ": ";
48
charCount = 0;
while (next != NWLN && !cin.eof()){
cout.put(next);
charCount++;
totalChars++;
cin.get(next);
} // end inner while to get a line
cout.put(NWLN);
lineCount++;
cout << "Number of characters in line "
<< lineCount << " is " << charCount << endl;
cout << "Enter a line or press " << ENDFILE << ": ";
// end outer while
49
CountChars.cpp (Output)
cout << endl << endl
<< "Number of lines processed is "
<< lineCount << endl;
cout << "Total number of characters is "
<< totalChars << endl;
return 0;
}
50
File I/O
Declare the stream to be processed:
#include <fstream>
ifstream ins;
ofstream outs;
// input stream
// output stream
outs.open(outFile);
51
Files
#define associates the name of the stream
52
CopyFile.cpp
Program Output
Input file copied to output file.
37 lines copied.
53
CopyFile.cpp (Header)
// File: CopyFile.cpp
// Copies file InData.txt to file OutData.txt
#include <cstdlib>
#include <fstream>
54
CopyFile.cpp (Declarations)
// Functions used ...
// Copies one line of text
int copyLine(ifstream&, ofstream&);
int main()
{
// Local data ...
int lineCount;
ifstream ins;
ofstream outs;
55
56
57
58
59
60
61