A Brief Look at C++: A Guide To Reading C++ Programs: - C Evolved From BCPL and B. BCPL Was
A Brief Look at C++: A Guide To Reading C++ Programs: - C Evolved From BCPL and B. BCPL Was
00 Lecture 37
C and C++
C evolved from BCPL and B. BCPL was
developed by Martin Richards in 1967. Ken
Thompson based B on BCPL and used it to write
very early versions of UNIX. These were
"typeless" languages. All data occupied same
amount of memory, and programmer had to deal
with data type differences.
C developed in 1972 by Dennis Ritchie at Bell
Lab.
C++ developed by Bjarne Stroustrup in ealry
1980s at Bell Labs to support OO programming
1
Areas C/C++ differ from Java
Not all code in objects
header files
preprocessor
Call by reference allowed
Pointers and pointer arithmetic
Array bounds checking
Garbage collection, destructors, memory leaks
Templates (parameterized data types)
Automatic instances of objects within a scope
implicit type conversion
operator overloading
multiple inheritance
virtual and non virtual methods
2
Call by reference example
#include <iostream.h>
void triple( int& base); // & means send reference
// Above usually in .h file
int main() {
int value;
cout << Enter an integer: ;
cin >> value;
triple( value);
cout << Tripled value is: << value << endl;
return 0;}
3
Pointer arithmetic
#include <iostream.h>
double average1(double b[], int n); // Function prototypes
double average2(double b[], int n);
int main() {
double values[]= {5.0, 2.3, 8.4, 4.1, 11.9};
int size= 5; // C++ arrays dont know their size
double avg1= average1(values, size);
double avg2= average2(values, size);
cout << "Averages are: " << avg1 << " and " << avg2 << endl;
return 0;}
b 5.0
2.3
8.4
4.1
11.9
4
Bracket Program (C, C++)
#include <math.h> // Obsolete, use #include <cmath>
#define FACTOR 1.6 // Obsolete, use const double FACTOR=1.6;
#define NTRY 50 // Use const int NTRY= 50;
int main() {
float n1= 7.0;
float n2= 8.0;
int bracketFound= zbrac(f, &n1, &n2);
cout << "Lower " << n1 << " upper " << n2 << endl;
return 0; }
5
Passing arguments: value, reference
w x y[2] variable
main: (doubles)
15.0 -8.0 4.5 6.7
void fun(double ww, double xx){} void fun(double& ww, double& xx, double yy[]){}
Point Class
// File Point.h
#include <iostream>
using namespace std;
class Point{
public:
Point (double a=0, double b=0); // Default constructor
~Point(){}; // Destructor
double getX(); // Prototype only
double getY();
void print();
Point addPoint (Point& g); // Choose value or ref
private:
double x, y;
} ;
6
Point Class, cont.
// File Point.C
#include Point.h
#include Point.h
int main(){
double a;
p3.print();
a= p3.getX();
return 0;}
7
Copy constructors in C++
In C++, objects are passed as copies in call by
value
By default, objects are copied "bitwise"
Objects that allocate memory in their constructors
(arrays, other objects) need a special constructor
that is equivalent of the clone( ) method in Java
Copy constructor takes reference to object, and
returns a new object of same class that is an
independent copy.
Copy constructors often get invoked implicitly. For
example, a method that returns a new object will
implicitly invoke copy constructor if one exists.
8
An Exquisite Point Class
// File Point.h
#include <iostream>
#include <cmath>
using namespace std;
class Point{
friend double distance1(const Point& p, const Point& q);
friend ostream& operator<<(ostream& os, const Point& p);
public:
Point(double a=0.0, double b=0.0); // Constructor
Point(const Point& p); // Copy constructor
Point operator+(const Point& p) const; // Add 2 Points
Point operator-() const; // Unary minus
Point& operator=(const Point& p); // Assignment
~Point() {}; // Destructor
private:
double x, y;
};
#include Point.h
{ x=a; y=b;}
Point::Point(const Point& p) // Copy constructor
{x=p.x; y=p.y;}
Point Point::operator+(const Point& p2) const // Add 2 Points
{ return Point(x+p2.x, y+p2.y);}
Point Point::operator-() const // Unary minus
{ return Point(-x, -y);}
Point& Point::operator=(const Point& p2) // Assignment
{ if (this != &p2) { // Check if p2=p2
x= p2.x;
y= p2.y;}
return *this;}
9
An Exquisite Point Class, p.3
// File Point.C with function bodies, continued
// Friend functions: distance and output (cout)
double distance1(const Point& p, const Point& q)
{ double dx= p.x - q.x;
double dy= p.y - q.y;
return sqrt(dx*dx + dy*dy);}
int main(){
Point p1(3,4), p2(2); // Use constructor, default args
Point p3(p2); // Use copy constructor
Point p4= Point(1,2); // Assignment operator(member copy)
p3= p1 + p2; // Same as p3= p1.operator+(p2)
p4= p1 + p2 + p3; // Chaining
p3= -p1; // Unary minus
p2= p4 + p1; // We could implement subtraction!
double a;
a= distance1(p1, p2);
cout << The distance from p1 to p2 is: << a << endl;
cout << p1= << p1 << and p2= << p2 << endl;
return 0; }
// Our Java matrix methods would be nicer with op overload!
10
Constructors and
Destructors
Dynamic memory allocation
Class Student
public:
Student()
{ pc= new courselist[ncourses];
pg= new gpalist[nterm];}
~Student( )
{ delete[ ] pc;
delete[ ] pg; }
Constructors and
Destructors, p.2
Main program
Joe int main() {
pc pg
{ //Func or block scope
Student Joe;
100 20 X } // End of scope
{ // Another scope
Student Mary;
Mary
pc pg
X
} // End of scope
}
100 20
11
Constructors and
Destructors, p.3
No memory management in main program or
functions, as a goal in C++
In C, memory was managed for each variable
You had to remember to allocate it and free it when done,
no matter where these events occurred.
Dynamic memory errors are over 50% of C program errors
In C++, we build memory management into classes
New only in constructors; delete only in destructors
Application developer sees nearly automatic garbage
collection. She never uses new; creates new objects just
by defining them: Student Joe, same as int i
Class developer has control of garbage collection when
needed
C++ garbage collection is tough on lists, trees, etc.
12
template <class TYPE>
class stack { Stack Template Class
public:
explicit stack(int size): max_len(size), top(EMPTY)
{s= new TYPE[size];}
~stack()
{ delete [] s;}
void reset()
{ top= EMPTY;}
void push(TYPE c)
{ assert(top != max_len -1) ; s[++top]= c;}
TYPE pop()
{ assert (top != EMPTY); return s[top--];}
TYPE top_of() const
{ assert (top != EMPTY); return s[top];}
bool empty()
{ return ( top == EMPTY);}
bool full()
{ return ( top == max_len -1);}
private:
enum {EMPTY = -1};
TYPE* s;
int max_len;
int top;};
if (!library.full())
library.push(a);
if (!library.full())
library.push(x);
if (!library.empty()){
book= library.pop();
cout << First shelved: " << book << endl;}
if (!library.empty()){
book= library.pop();
cout << "Earlier book, later shelved: " << book << endl;}
if (!library.full())
library.push(g);
book= library.top_of();
cout << "Next book returned: " << book << endl;}
13
Inheritance: Access Specifiers
class Base : {
public:
protected:
private: };
{ cout << firstName << " " << lastName << " ";}
private:
string firstName, lastName;
};
// implement GetPay()
14
Undergrad
class Undergrad : public Student {
public:
Undergrad(string fName, string lName, double hours,
double rate); // Body in different file
double GetPay() const
{ return UnderWage * UnderHours;}
virtual void GetData() const
{
Student::GetData(); // Instead of super.GetData()
cout << "weekly pay: $" << GetPay() << endl;
}
private:
double UnderWage;
double UnderHours;
};
// Same model for grad, special grad classes
15
Research project class, p.2
RProject::RProject(int Size) {
StaffSize= Size;
StaffList= new Student*[StaffSize];
count= 0;}
void RProject::listPay() {
cout << "Project staff " << endl;
for (int i= 0; i < count ; i++)
StaffList[i]->GetData(); // (*StaffList[i]).GetData()
return; }
16
Main program
int main( ) {
// Define 3 students (unchanged from last time)
Undergrad Ferd("Ferd", "Smith", 8.0, 12.00);
Ferd.GetData();
Grad Ann(Ann", "Brown", 1500.00);
Ann.GetData();
SpecGrad Mary("Mary", "Barrett", 2000.00);
Mary.GetData();
cout << endl;
Other Items
Exceptions essentially same as Java
Try, throw, catch
Standard template library (STL) with Vectors,
Lists, Stacks, similar to Java
Cannot inherit from STL classes
Multiple inheritance supported
C has two string types (with conversions)
Null terminated arrays (old)
String class
Arrays are just a memory location (reference)
Array size is passed as separate argument
Very problematic (buffer overruns)
Recursion supported as in Java
17