Overloading Assignment
Overloading Assignment
class linklist
{
private:
link* first; // pointer to first link
public:
linklist() { first = NULL;} // no argument constructor
void additem(int d); // add data item (one link)
void display(); // display all links
}
Linked List Example
void linklist::additem(int d) // add data item
{
link* newlink = new link; // create a new link
newlink->data = d; // give it data d
newlink->next=first; // it points to the next link
first = newlink; // now first points to this link
}
void linklist::display() // display all links
{
link* current=first; // set ptr to first link
while(current != NULL) // until ptr points beyond last link
{
cout << current->data << ” ”; // print data
current=current->next; // move to next link
}
}
Linked List Example
l2
2 5 3
Overloading Assignment
linklist& linklist::operator=(linklist &list) // assignment operator
{
while (first !=NULL) // first empty list
deleteitem();
class linklist
{
public:
linklist() { first = NULL;}
linklist( linklist& list) { *this=list; } // copy constructor
…
};
Multiple Inheritance
base class A subclass
Feature A Feature A
Feature B Feature B
Feature C
base class B
Feature D
Feature C
Feature D
Multiple Inheritance
class Date
{
private:
int day, month, year;
…
};
class Time
{
private:
int hours, minutes;
…
};
Multiple Inheritance
class DateTime : public Date, public Time
{
public:
DateTime(int d, int m, int y, int h, int mi)
: Date(d,m,y), Time(h, mi) {};
…
};
Ambiguity in Multiple Inheritance
class Date
{
void add(int days);
};
class Time
{
void add(int minutes);
};
DateTime dt(13,2,1998,23,10);
dt.add(3); // ambiguous -- will not compile
dt.Date::add(4); // uses add of class Date
dt.Time::add(5); // uses add of class Time
Ambiguity in Multiple Inheritance
class A { public: void F(); };
class B : public A { …};
class C : public A { …};
class D : public B, public C {};
D d;
d.F(); // ambiguous - won´t compile
class A
diamond shaped
inheritance tree
class B class C
class D
Streams and Files
A stream is a flow of data. In C++ streams are represented by
objects of the class ios and its subclasses.
Different types of streams represent different kinds of data flow,
for example the class ifstream represents data flow from input
disk files.
The advantage of streams compared to traditional C-functions
fstream.h
iostream
ifstream ofstream
fstream
istream_ ostream_
withassign iostream_ withassign
withassign
Stream Class Hierarchy
ios : is the base class that contains constants and member
functions common to input and output operations. It also
contains a pointer to streambuf which contains the actual
memory buffer into which data is read or written.
istream, ostream, iostream : are derived from ios, are
dedicated to input and output and contain functions such
as
istream: get(), getline(), read() and the >> operator
#include <iomanip>
float x=3.14259;
cout << “[“ << setw(8) << setprecision(4) << setiosflags(ios::left) << setfill(‘*’)
<< x << “]” << endl; // displays [3.143***]
Functions
The ios class contains a number of functions that can
be used to set formatting flags.
fill(int) : sets fill character
cout.width(5);
cout.precision(6);
cout.setf(ios::left);
Istream Class
The istream class, derived from ios, performs input-specific activities or
extraction.
>> : extraction operator
read(str, MAX) : (for files) extract up to MAX characters into str until EOF
char ch=‘n’;
while(ch) != ‘y’) {
cout << “Enter y : “ << endl;
cin.get(ch); }
Ostream Class
The ostream class, derived from ios, performs output-specific
activities or extraction.
<< : insertion operator
into file
cout.put(‘a’);
cout.flush();
Iostream with Assign
istream_withassign, ostream_withassign,
iostream_withassign are identical to istream, ostream
and iostream except that stream objects can be
copied.
Normally the stream objects can not be copied as
they point to the same streambuf object
Stream Errors
The stream error-status flags report errors that occur in input or
output operations.
Various ios functions can be used to read and set these error flags.
eofbit : reached end of file
goodbit : no errors
#include <fstream>
int n=12;
string str= “Shakespeare”;
ofstream outfile(“data.txt”); // create ofstream object
outfile << n << “ th Night was written by “ << str << endl;
outfile.close(); // explicitly closes the file
Disk I/O with File Streams
#include <fstream>
const int BUF_SIZE = 80;
char buffer[BUF_SIZE]; // character buffer
ifstream infile(“test.txt”);
while ( !infile.eof() ) // until end of file
{
infile.getline(buffer,BUF_SIZE); // read a line of text
cout << buffer << endl; // display it
}
Character I/O
The put() and get() functions can be used to output and input
single characters.
#include <fstream>
#include <string>
string str=“Love sees not with the eye but with the mind and
therefore Cupid’s wings are painted blind”;
ofstream outfile(“text.txt”); // create file for output
for (int i=0; i<str.size(); i++) // for each character
outfile.put( str[i] ); // write char to file
outfile.close();
Character I/O
#include <fstream>
char ch;
ifstream infile(“text.txt”); // create file for output
while ( ! infile.eof() ) // read until end of file for (int i=0; {
{
infile.get(ch); // read character
cout < ch; // display it
}
infile.close();
Mode Bits for Opening Files
The open() function can be used to open a file:
The mode bits specify how the stream object is opened
Date d1(16,3,1998);
ofstream datefile(”dates.txt”);
datefile << d1 << endl;
Exceptions
Exceptions provide a systematic, object-oriented
approach to handle run-time errors generated by C++
classes.
Exceptions are errors that occur at run-time, for example
caused by running out of memory, not being able to
open a file or using out-of-bounds index to a vector.
In C errors are usually signaled by the return status of a
function. The drawback is that after each call to a
function it is necessary to examine the return value,
which requires a lot of code and makes the listing hard
to read.
Exceptions
Class Application
try block
Member correct call
Code that
functions normal return
interacts
with class
incorrect call
error
catch block
exception Error
handling
code
Exceptions
int d,n;
char dummy;
while (d==0) {
try // try block
{
cout << “enter a/b”;
cin >> n >> dummy >> d;
frac f(n,d); // calls constructor for frac
}
catch(frac::fracerror) // exception handler
{
cout << “denumerator 0 not allowed” << endl;
}
}
Exceptions
class Vec
{
private:
int size;
double *array;
public:
class Range {}; // exception class for Vec
double operator[] (int index)
{
if ((index <0) || ( index >= size))
throw Range();
else return array[index];
}
};
Exceptions
Vec x;
try { // try block
x.push_back(12.0);
x.push_back(3.0);
x.push_back(5.0);
x.push_back(2.3);
cout << x[5] << endl; // ooops, no 5th element
}
catch (Vec::Range) // exception handler
{
cout << “ Index out of range “ << endl;
}