Documente Academic
Documente Profesional
Documente Cultură
Piyush Kumar
| Use of svn is mandatory. (version | Re-Read code. More eyes will help
control) make better quality. Read code from
z “The palest of ink is better than the best memory”
z Don’t break the build. The code in the version control
good programmers. You’ll learn and
system (svn) should always compile. benefit.
| Lot of svn tutorials on the web.
| It’s best to do code reviews in writing,
z http://artis.imag.fr/~Xavier.Decoret/res
ources/svn/index.html a simple e-mail can suffice.
z http://centerstageproject.com/wiki/inde
x.php/SVN_Tutorial
| Write code for people first, then | Remember, “It is far easier to make a
machines. correct program fast than to make a
fast program correct”.
COP 3330 Object Oriented Programming in C++ Lecture Slides 1/134 (c) pk
1
Global variables. Coding Style
| Minimize global and shared data. | Prefer compile and link time errors to
z Example. You are not allowed to use run time errors.
“static” keyword in your code (till | Use “const” proactively.
asked). | Avoid macros.
z Information Hiding: Don’t expose | Avoid Magic numbers.
internal information from an entity that | Declare variables as locally as
provides an abstraction. possible.
| Always initialize variables.
COP 3330 Object Oriented Programming in C++ Lecture Slides 2/134 (c) pk
2
Documentation Generators
Piyush Kumar
| For each project that uses Doxygen, | Well documented, you just need to fill in the
you must create a configuration file. blanks.
| Main things to set
| “doxygen –g” creates a example
z PROJECT_NAME = MyProject
configuration file called “Doxyfile”
z OUTPUT_DIRECTORY = ./doc
| “doxygen [configfile]” will create the z INPUT = ./src ./include
documentation for your code as per z FILE_PATTERNS = *.cpp *.hpp
your configuration specs. z GENERATE_HTML = YES
z EXTRACT_ALL = YES
COP 3330 Object Oriented Programming in C++ Lecture Slides 3/134 (c) pk
1
Documenting the source. Documenting the source.
Here you should tell us about how your project works. How to run,
| Don't just re-express the algorithm in
any special things you have, etc. Also, explain any non-trivial
design decisions you make. If you are working with a partner, clearly
English; tell us why you're doing something.
State what is each person’s contribution. You should
also comment on the stability of your code. Any big bugs should be listed
here. Basically, anything that you think we need to know in general about
your project should go here. Right: For each name in the array, extract the lastname.
Any additional comments you want to make can go here. Did you like the Wrong: Set i to 0. Loop from 0 to 10. Call strchr() on a[i],
project? Was it too hard, too easy? My TA smells bad. Well, you get looking for the first ' ' character. Return the pointer
the idea.
the character immediately following the ' '.
This initial documentation here should be removed.
Or else you loose points.
*/
Documentation Rules
| For each project, create a directory
structure like this:
prj_?\
Doxyfile Created using doxygen –g
Makefile Modify it after creation.
README
bin\
data\
doc\
include\
src\
COP 3330 Object Oriented Programming in C++ Lecture Slides 4/134 (c) pk
2
Setting up svn
| Run
For : COP 3330.
svn ls https://svn.cs.fsu.edu/repos/team1
Object oriented Programming (Using C++)
z lists all files in your repository. (empty)
http://www.compgeom.com/~piyush/teach/3330
Piyush Kumar
COP 3330 Object Oriented Programming in C++ Lecture Slides 5/134 (c) pk
1
The extra .svn Working with the project
piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1>ls -la
total 132 $ svn add src/class.h src/class.cpp
drwx------ 8 piyush CS-Faculty 4096 Aug 30 23:02 .
drwx------ 4 piyush CS-Faculty 4096 Aug 30 23:02 .. A src/class.h
drwx------ 3 piyush CS-Faculty 4096 Aug 30 23:02 bin
drwx------ 3 piyush CS-Faculty 4096 Aug 30 23:02 data A src/class.cpp
drwx------ 3 piyush CS-Faculty 4096 Aug 30 23:02 doc
-rw------- 1 piyush CS-Faculty 47593 Aug 30 23:02 Doxyfile $ svn commit –m “Added two files”
drwx------ 3 piyush CS-Faculty 4096 Aug 30 23:02 include
-rw------- 1 piyush CS-Faculty 96 Aug 30 23:02 Makefile
-rw------- 1 piyush CS-Faculty 39 Aug 30 23:02 README
drwx------ 3 piyush CS-Faculty 4096 Aug 30 23:02 src
drwx------ 7 piyush CS-Faculty 4096 Aug 30 23:02 .svn
piyush@linprog4.cs.fsu.edu:~/cop3330/prj_1>
Project Submission
COP 3330 Object Oriented Programming in C++ Lecture Slides 6/134 (c) pk
2
Compiling programs
Piyush Kumar
COP 3330 Object Oriented Programming in C++ Lecture Slides 7/134 (c) pk
1
Make and Makefiles An example
are executable or object files. A target can also hello: main.o sumof.o hello.o
be the name of an action to carry out, such as Command g++ main.o sumof.o hello.o -o hello
COP 3330 Object Oriented Programming in C++ Lecture Slides 8/134 (c) pk
2
Make Another Example: Makefile-2
| Makefile-2 Comments in makefile.
| Only makes out of date prerequisites.
# The variable CC will be the compiler to use.
hello: main.o sumof.o hello.o CC=g++
Variables
g++ main.o sumof.o hello.o -o hello # CFLAGS will be the options I'll pass to the compiler.
CFLAGS=-c -Wall -g
all: hello
| How to decide whether “hello” is out Using hello: main.o sumof.o hello.o
$(CC) main.o sumof.o hello.o -o hello
Variables
of date? main.o: main.cpp
$(CC) $(CFLAGS) main.cpp
z It is out of date if it does not exist, sumof.o: sumof.cpp
or $(CC) $(CFLAGS) sumof.cpp
z if either main.o , sumof.o or hello.o are more recent than it. hello.o: hello.cpp
$(CC) $(CFLAGS) hello.cpp
clean:
If “hello” is out of date, make executes the command ‘g++ main.o …’ rm -rf *o hello *.exe
COP 3330 Object Oriented Programming in C++ Lecture Slides 9/134 (c) pk
3
Administrative Trivia
Your ID Announcement
You have been assigned an ID on the | First Quiz : On Thursday. Will test
Blackboard. You should know your ID. your background knowledge.
| Revise your previous C/C++ material.
| Your first assignment will be posted
Your ID will be used to setup your
on Wednesday.
Subversion (svn) repository.
z Will be due on Tuesday, 9/5/06.
z You are required to setup your svn
http://www.compgeom.com/~piyush/teach/3330/handouts/SVN_Setup.pdf repository by this Thursday. The
submission will use the svn server.
Announcement
COP 3330 Object Oriented Programming in C++ Lecture Slides 10/134 (c) pk
1
Why learn C++? C++ Features
Compiling/Running
Important definitions
programs
| Algorithm: Ordered set of actions to | Single source file code:
accomplish a certain task. z g++ -g –Wall simple.cpp –o simple
COP 3330 Object Oriented Programming in C++ Lecture Slides 11/134 (c) pk
2
simple.cpp simple.cpp
int main() // Function Declaration | On Unix: echo $?
// Function body follows | On Windows: echo %ERRORLEVEL%
return 0;
} // Block ends.
System dependent
G++ Compilation.
preprocessing (to expand macros)
|
|
z Try “cpp simple.cpp > simple.i”
compilation (from source code to assembly language)
Introduction to C++
z Try “g++ -Wall –S simple.i”
| assembly (from assembly language to machine code)
z Try “as simple.s -o simple.o”
| linking (to create the final executable)
z Try “gcc simple.o”
z Equivalent to “ld -dynamic-linker /lib/ld-linux.so.2
/usr/lib/crt1.o /usr/lib/crti.o /usr/lib/gcc-
lib/i686/3.3.1/crtbegin.o -L/usr/lib/gcc-lib/i686/3.3.1
hello.o -lgcc -lgcc_eh -lc -lgcc -lgcc_eh /usr/lib/gcc-
lib/i686/3.3.1/crtend.o /usr/lib/crtn.o”
$ file ./a.exe Æ Identify type of file generated (gcc on windows).
./a.exe: PE executable for MS Windows (console) Intel 80386 32-bit
COP 3330 Object Oriented Programming in C++ Lecture Slides 12/134 (c) pk
3
Organization C++ is a superset of C.
COP 3330 Object Oriented Programming in C++ Lecture Slides 13/134 (c) pk
4
Another Object / Class Fundamental building block
example of OOP: A Class
class Point { | A class defines a data type, much like
int _x, _y; // point coordinates a struct would be in C.
public: // begin interface section | A class is a source code for an object
tpoint._x = 5; // ILLEGAL
COP 3330 Object Oriented Programming in C++ Lecture Slides 14/134 (c) pk
5
Data Abstraction Data Encapsulation
| Many classes have common attributes. | Children inherit traits from their
| These classes can be arranged in a parents.
hierarchy.
| When a class is inherited all the
| Inheritance enables you to reuse code and functions and data member are
add data and functionality without making
any changes to the existing code.
inherited, although not all of them will
z For example, objects can inherit
be accessible by the member
characteristics from other objects. functions of the derived class.
Inheritance Inheritance
COP 3330 Object Oriented Programming in C++ Lecture Slides 15/134 (c) pk
6
Multiple definitions…? Operator Overloading
| C++ allows for the same function (or | C++ gives you the power to define operators
overloaded operator) to have multiple on user defined types.
defintions. | Example:
z Swap(int& I, int& j); z MyMatrix m = m1 + m2; // cant do this in C.
z Swap(string& I, string& j); | Overloading is a type of polymorphism.
z Swap(double& I, double& j);
| Not all operators can be overloaded in C++.
a.k.a. Function overloading.
Polymorphism Methods:
Draw() Polymorphism Methods:
Draw()
MyShape Erase() MyShape Erase()
Circle Square Triangle Sphere Cube Tetrahedron Circle Square Triangle Sphere Cube Tetrahedron
| Base Class MyShape establishes the | Overriding: When a child class extends the
functionality of its parent class.
common interface to anything | Polymorphism allows the programmer to
inherited from MyShape. implement different draw/erase methods for
derived classes.
| All shapes can be drawn and erased.
| Sphere and Cube have the same function
draw() with different functionality.
Polymorphism Methods:
Draw() Polymorphism
MyShape Erase()
2DShape 3DShape
| Using operators and functions in
different ways depending on what
Circle Square Triangle Sphere Cube Tetrahedron they are operating on is called
polymorphism.
| No matter what shape the object is, z Static
one can use the “draw” method to z Dynamic
draw it correctly.
| The concept builds upon
encapsulation and inheritance.
COP 3330 Object Oriented Programming in C++ Lecture Slides 16/134 (c) pk
7
Generic Programming
COP 3330 Object Oriented Programming in C++ Lecture Slides 17/134 (c) pk
8
Basic C++ Types
Basic and Library | integer data-types :
Types |
char, short, int, long, unsigned char, unsigned short,…
floating point data-types :
float, double, long double
| logical data-type : bool
z bool constants : true, false
For : COP 3330.
| character data-type : char and wchar_t
Object oriented Programming (Using C++) z Char constants in single quotes : ’a’
http://www.compgeom.com/~piyush/teach/3330 | text data-type :
string
string constants in double quotes : ”Hello world”
Piyush Kumar
Recommended assignments:
2.4/2.7/2.8/2.9
COP 3330 Object Oriented Programming in C++ Lecture Slides 18/134 (c) pk
1
Hungarian Base Types Prefixes
| Specifies the type of the variable being named | Go in front of the base type
| Somewhat standard list:
| Not for predefined types z a = Array
| Example: z c = Count
z d = Difference
z wn = Window
z e = Element of an array
z scr = Screen z g = Global variable
z fon = Font z h = Handle
z i = index to array
z pa = Paragraph
z m = Module-level variable
| Example: z p(np, lp) = Pointer (near or long)
z WN wnMain=NULL; | Describes how the variable will be used.
| Examples
z FONT fonUserSelected = TIMES_NEW_ROMAN; z Array of windows: awnDialogs
z Handle to a window: hwnMyWindow
z Number of fonts: cfon
Variables Variables
Type specifier
COP 3330 Object Oriented Programming in C++ Lecture Slides 19/134 (c) pk
2
Recommended
Exercises: 2.15/2.16
COP 3330 Object Oriented Programming in C++ Lecture Slides 20/134 (c) pk
3
References References
Here i and j are aliases for main's x and y respectively. In other words,
i is x — not a pointer to x, nor a copy of x, but x itself. Anything you do
to i gets done to x, and vice versa.
COP 3330 Object Oriented Programming in C++ Lecture Slides 21/134 (c) pk
4
Class example 2D Point class
#endif
public: public:
void setX(const int val) { void setX(const int val) ;
_x = val;
} // … Rest of the interface/implementation…
};
// … Rest of the interface/implementation…
}; typedef point2D Cell_tower;
typedef point2D Cell_phone;
typedef Point2D Cell_tower;
typedef Point2D Cell_phone; // Implementation goes here…
void point2D::setX(const int val){ Can be also
// Implementation goes here… _x = val; implemented
} in point2D.cpp
#endif
#endif
COP 3330 Object Oriented Programming in C++ Lecture Slides 22/134 (c) pk
5
Headers Header files
Header file
| max(++a,b)
| max(++a,b+10)
COP 3330 Object Oriented Programming in C++ Lecture Slides 23/134 (c) pk
6
C++ IO
Piyush Kumar
| cout standard output stream | More type-safe: With <iostream>, the type of object
being I/O'd is known statically by the compiler. In
sequence of characters printed contrast, <cstdio> uses "%" fields to figure out the
to the monitor types dynamically.
| Less error prone: With <iostream>, there are no
redundant "%" tokens that have to be consistent with
| cin standard input stream the actual objects being I/O'd. Removing redundancy
sequence of characters input removes a class of errors.
from the keyboard | Extensible: The C++ <iostream> mechanism allows
new user-defined types to be I/O'd without breaking
existing code. Imagine the chaos if everyone was
simultaneously adding new incompatible "%" fields to
| both cout and cin are data objects printf() and scanf()?!
and are defined as classes | Inheritable: User defined streams possible.
cin cout }
( type istream ) ( type ostream ) Stream: A flow of characters (1 or 2 bytes long). Can flow in and out of
Files, strings, etc.
class class
COP 3330 Object Oriented Programming in C++ Lecture Slides 24/134 (c) pk
1
Example Example invokes a manipulator function called endl.
endl looks something like this:
filebuf
COP 3330 Object Oriented Programming in C++ Lecture Slides 25/134 (c) pk
2
C++ IO Class hierarchy C++ IO Hierarchy
ios
| The ios hierarchy defines the
istream
cin
ostream
cout
streambuf interface of the IO system.
| The streambuf hierarchy defines the
ifstream istringstream ostringstream ofstream implementation of the IO system,
mostly provides the facilities of
buffering and byte-level I/O
stringbuf
filebuf
Stream IO Example
Inside ios
COP 3330 Object Oriented Programming in C++ Lecture Slides 26/134 (c) pk
3
<< operator << operator
| Associates from left to right, and returns a reference to
| << is overloaded to work on built-in its left-operand object (i.e. cout). This enables
types of C++. cascading.
| Outputs “char *” type as a string.
| Can also be used to output user-
| If you want to print the address, typecast it to (void *).
defined types. | Example:
z char name[] = “cop3330”;
| Other interesting examples:
z cout << name << static_cast<void *>( name ) << endl;
z cout << ‘\n’; // newline. z static_cast<void *>( name ) equivalent to ((void *)
z cout << “1+2=” << (1+2) << endl; name) in C except that it happens at compile time.
z cout << endl; // newline.
z cout << flush; // flush the buffer.
using std::cout;
while (cin >> fname) using std::cin;
using std::endl;
int main(void) {
“>>” returns 0 (false) when EOF int height = 0, maxheight = 0;
encountered and loop terminates. cout << "Enter the heights: (enter end of file to end): ";
while(cin >> height)
if( height > maxheight)
maxheight = height;
COP 3330 Object Oriented Programming in C++ Lecture Slides 27/134 (c) pk
4
Output istream member function: get
| Read in up to 255 characters and inserts | Same as get, except that getline
a null at the end of the string “fname". If
a delimiter is found, the read terminates. discards the delimiter from the stream.
The array acts like a buffer. The
delimiter is not stored in the array, but is
left in the stream.
COP 3330 Object Oriented Programming in C++ Lecture Slides 28/134 (c) pk
5
FILE IO Example. Slightly modified
Copy File “first.txt” into “second.txt”. #include <iostream>
#include <fstream>
#include <iostream>
#include <fstream> using namespace std;
COP 3330 Object Oriented Programming in C++ Lecture Slides 29/134 (c) pk
6
#include <iomanip>
dec, hex, oct, setbase
Stream | oct, hex, dec
Manipulators z Cout << hex << 15;
• Prints ‘F’
| cout << setbase(16) << 15;
z Prints ‘F’ again.
COP 3330 Object Oriented Programming in C++ Lecture Slides 30/134 (c) pk
7
Using the default - Integers p.5
General Rule of Thumb
| Note on field widths: if a field width specified is
too small, or is not specified, it is automatically
expanded to minimum required | When you are printing numeric values in
sentences or after a verbal label, the default
| numstdts = 100; field width usually works well
cout << “FSU has "
<< numstdts << " students." | When you are printing numeric values lined
prints up in columns in a table, it is usually
necessary to call setw to generate well-
FSU has 100 students. formatted output (we will see examples of
this later in the course)
and works for any value of numstdts
COP 3330 Object Oriented Programming in C++ Lecture Slides 31/134 (c) pk
8
Formatting Output - char Formatting Output - Strings
| default field width == 1 | default field width == number of
note: setw does have effect on characters in the string
char type data too.
can use setw
char ch = 'Q';
cout << '*' << ch << setw(3) << '*'; cout << setw(10) << "Hello";
prints
prints Hello
*Q *
COP 3330 Object Oriented Programming in C++ Lecture Slides 32/134 (c) pk
9
Error states
strm::eofbit
Stream Error States |
z if (cin.eof() == true) break; // stream end of file.
| strm::failbit
z if ( cin.fail() == true) break; // stream format error.
| strm::badbit
z If (cin.bad() == true) break; // data lost!
| Goodbit?
z cin.good() = ((!eofbit) && (!failbit) && (!badbit))
z All eofbit, failbit and badbit should be false.
| cin.clear() // makes cin good.
prompt typically contains prefix cout << "Enter a number -> ";
character to signal point at which to cin >> num;
enter input
cout << "Enter Y or N -> ";
| Read value(s) cin >> response;
user types data at keyboard
COP 3330 Object Oriented Programming in C++ Lecture Slides 33/134 (c) pk
10
Interactive Input: Contents of Another C++ Program
Output Window (Hello argv[1])
#include <iostream>
using namespace std;
Enter a number -> 17<return>
int main(int argc, char *argv[]) {
if (argc != 2) {
cout << "Usage: hi.exe <name>" << endl;
Enter Y or N -> Y<return> exit (1);
}
Control structures
COP 3330 Object Oriented Programming in C++ Lecture Slides 34/134 (c) pk
11
The C++ Standard Library
Introduction to the | Provides the ability to use:
C++ Standard Library. z String Types
z Data Structures (linked list, dynamic
arrays, priority queues, binary trees etc)
For : COP 3330. z Algorithms (Sorting and Searching…)
Object oriented Programming (Using C++)
z IO
http://www.compgeom.com/~piyush/teach/3330
z Classes for internationalization support.
Piyush Kumar
COP 3330 Object Oriented Programming in C++ Lecture Slides 35/134 (c) pk
1
Containers Containers
COP 3330 Object Oriented Programming in C++ Lecture Slides 36/134 (c) pk
2
An example usage An example usage
#include <vector> #include <vector>
#include <iostream> #include <iostream>
Iterators Iterators
Iterators Iterators
| Support the following operations:
| Container.begin() : All containers z Operator * : Element at the current position
support a function called begin, which (example: (*it)). You can use “->” to access
object members directly from the iterator.
will return an iterator pointing to the (Like a pointer)
beginning of the container (the first z Operator++ : Moves the iterator to the next
element) element. Most iterators will also allow you to
| Container.end() : returns an iterator use “ - - ” for stepping back one element.
corresponding to having reached the z Operator == and != : Compare two iterators
for whether they represent the same position
end of the container. (Not the last (not the same element).
element) z Operator = : Assigns an iterator.
COP 3330 Object Oriented Programming in C++ Lecture Slides 37/134 (c) pk
3
Iterators Iterators
COP 3330 Object Oriented Programming in C++ Lecture Slides 38/134 (c) pk
4
Random Access Iterators Back to vectors
| Iterator type: Random-access
| Allow arithmetic | Operator [] overloaded
z it+n v.size() Number of elements in vector
z The result will be the element corresponding
v.Clear() Removes all elements
to the nth item after the item pointed to be
the current iterator. v.pop_back() Removes last element
z it – n also allowed v.push_back( elem ) Adds elem at end of vector
z (it1 – it2) allowed
• Example: Type of this operation for vectors is v.insert(pos,elem) Inserts elem at position pos and
returns the position of the new
defined by vector<T>::difference_type.
element.
v.erase(pos) Removes the element at the
Another form: iterator position pos and returns
v.erase(bpos,epos) the position of the next element.
COP 3330 Object Oriented Programming in C++ Lecture Slides 39/134 (c) pk
5
What can a container
Suggestions
contain?
| Minimal constraint on elements of a | Prefer vector and string to dynamically
container. allocated arrays.
z Operator= | Use reserve() to avoid unnecessary
• a = b; should be valid reallocations.
z A copy constructor | Avoid using vector<bool>
• YourType b(a); should be valid
| Question :
z Is vector<int&> allowed?
Understand Complexity
Algorithms
Example: Vector Insert
| Methods that act on containers (may or may What happens when the
not change them) vector is large?
firstName[5] = ‘h’
Intro To The Standard string
Some string Functionality
firstName[6]
Class | Declaring a string:
is undefined unlike
C where its ‘\0’.
z string lastName;
| C++ has a standard class called "string" z string firstName(“Piyush”); //Note: String literal enclosed in double quotes
| Strings are simply a sequence of characters z string fullName;
z Note: This is not a sufficient definition for a "C-string" | Assigning a string:
z A "C-string" is an array of characters terminated by a z lastName = “Kumar”; //The usual assignment operator
null byte | Appending one string on the end of another:
| Must #include <string> using the standard namespace to z fullName = firstName + lastName; //Results in “PiyushKumar"
get C++ standard string functionality z fullName = firstName + " " + lastName; //Results in “Piyush Kumar"
z Note: This is different from #include'ing <string.h> | Accessing individual characters in a string:
which is the header required for "C-string"s z myChar = firstName[4]; //Results in ‘s' (no bounds checking)
| string variables are used to store names, words, phrases, z myChar = firstName.at(4); //Results in ‘s' (does bounds checking)
etc. | Appending a character to the end of a string:
| Can be input using ">>" and output using "<<" as other z lastName = lastName + myChar; //Results in “Kumars"
types | Determining number of characters in string:
z myInt = firstName.length(); //Results in 6
COP 3330 Object Oriented Programming in C++ Lecture Slides 40/134 (c) pk
6
string Example #1 Constructors
Length of Drew is: 4
Length of Morgan is: 6
Length of DrewMorgan is: 10
string() // empty string
#include <iostream>
#include <string>
using namespace std;
Length of Morgan is: 6 string(string s) // copy of s
Length of Drew Morgan is: 11
int main(void)
{ Length of Morgan is: 6 string(string s, int start) // substring start,end
string first;
string last("Morgan"); string(string s, int start, int len) // substring
first = "Drew"; //Would be illegal for C-string
cout << "Length of " << first << " is: " << first.length() << endl; string(char* a) // copy of C-string
cout << "Length of " << last << " is: " << last.length() << endl;
first += "Morgan";
string(int cnt, char c) // one or more chars
cout << "Length of " << first << " is: " << first.length() << endl;
cout << "Length of " << last << " is: " << last.length() << endl; string(char* beg, char* end) // [beg, end)
first.assign("Drew");
first.append(" ");
first.append(last);
cout << "Length of " << first << " is: " << first.length() << endl;
cout << "Length of " << last << " is: " << last.length() << endl;
return(0);
}
Additional string
Other overloaded operators
Functionality
| Strings can be compared with usual operators | = is used to assign a value (char, C-string,
z >, >= (greater than, greater than/equal to) or string) to a string.
z <, <= (less than, less than/equal to) | += is used to append a string, character, or
z == (equality) C-string to a string.
| Strings also have a member function called "compare" | + is used to concatenate two strings or a
z int string::compare(string rhs); string with something else
z Return value is negative if calling string is less than rhs
| << and >> are used for input and output. On
z Return value is positive if calling string is greater than rhs
input, leading whitespace is skipped, and
z Return value is zero if both strings are identical
the input terminates with whitespace or end
of file.
COP 3330 Object Oriented Programming in C++ Lecture Slides 41/134 (c) pk
7
String Operations string Example #2
s3 = "Drew";
if (s3 < s1)
int main(void)
cout << "oper: s3 less than s1";
{
if (s3 > s1)
s.replace(various); // replaces string s1 = "Drew";
string s3;
cout << "oper: s3 greater than s1";
if (s3 == s1)
characters int result;
cout << "oper: s3 is equal to s1";
cout << endl;
s3 = "Bob";
s.size(); or s.length(); // how many if (s3 < s1)
result = s3.compare(s1);
cout << "oper: s3 less than s1";
characters? if (s3 > s1)
if (result < 0)
cout << "comp: s3 less than s1";
cout << "oper: s3 greater than s1";
s.max_size(); // maximum number of if (s3 == s1)
cout << "oper: s3 is equal to s1";
else if (result < 0)
cout << "comp: s3 greater than s1";
char? cout << endl;
else
cout << "comp: s3 is equal to s1";
cout << endl;
s.empty(); // is s empty? result = s3.compare(s1);
if (result < 0)
return (0);
cout << "comp: s3 less than s1";
s.reserve(cnt); // reserves memory else if (result < 0)
}
cout << "comp: s3 greater than s1"; oper: s3 less than s1
else comp: s3 less than s1
cout << "comp: s3 is equal to s1";
cout << endl;
oper: s3 is equal to s1
comp: s3 is equal to s1
COP 3330 Object Oriented Programming in C++ Lecture Slides 42/134 (c) pk
8
str += "-111-";
Example #4 cout << "Str: " << str << endl;
cout << "Length: " << str.length();
C Vs C++: Strings
int main(void) cout << " Cap: " << str.capacity();
{ cout << endl;
string str;
string str2; str += "1723-9"; C Library Functions C++ string operators
cout << "Str: " << str << endl;
cout << "Str: " << str << endl; cout << "Length: " << str.length(); /member functions.
cout << "Length: " << str.length(); cout << " Cap: " << str.capacity();
cout << " Cap: " << str.capacity(); cout << endl; strcpy =
cout << endl;
str = "888";
str += "abcdefghijklmnopqrstuv";
cout << "Str: " << str << endl;
strcat +=
cout << "Length: " << str.length();
cout << "Str: " << str << endl;
cout << "Length: " << str.length(); cout << " Cap: " << str.capacity(); strcmp = =, !=, <, >, <=, >=
cout << " Cap: " << str.capacity(); cout << endl;
cout << endl; strchr, strstr .find( ) method
return (0);
Str:
Length: 0 Cap: 0
} strrchr .rfind( ) method
Str: 888
Length: 3 Cap: 31 strlen .size( ) or .length( )
Str: 888-111-
Length: 8 Cap: 31
methods
Str: 888-111-1723-9
Length: 14 Cap: 31
Str: 888-111-1723-9abcdefghijklmnopqrstuv
Length: 36 Cap: 63
COP 3330 Object Oriented Programming in C++ Lecture Slides 43/134 (c) pk
9
Solution to assignment 1 Solution to assignment 1
sort(vs_inpvec.begin(), vs_inpvec.end());
vector<string> vs_inpvec; int i_inp_elements = vs_inpvec.size();
string s_one_entry; cout << "Input Elements = " << i_inp_elements << endl;
int counter = 0;
while( getline( cin, s_one_entry) ){ vs_inpvec.erase(
int _pos = s_one_entry.rfind('/'); unique(vs_inpvec.begin(), vs_inpvec.end()) ,
if(_pos != -1) vs_inpvec.end()
s_one_entry = s_one_entry.substr(_pos+1, s_one_entry.size() ); );
Example
// create a bitset out of a number
bitset<8> bs2( (long) 131 );
cout << "bs2 is " << bs2 << endl;
Output?
bs2 is 10000011
now bs2 is 00110000
Recommended Exercise:
3.23, 3.21, 3.18, 3.15
COP 3330 Object Oriented Programming in C++ Lecture Slides 44/134 (c) pk
10
Introduction To Pointers
Piyush Kumar
Operator 1001
1002 6 4 i
| Like the &, the * operator has another meaning as well 1003
| The * operator is usually referred to as the "dereference operator" int i = 6; //Declares integer called i 1004
| The * operator operates on a pointer value int *iPtr; //Declares a pointer to an int
1005
z The meaning is "Use the value that this pointer points to, rather than the
iPtr = &i; //Sets the iPtr variable to 1006 1000 iPtr
value contained in the pointer itself"
//contain the "address of" the 1007
| If a pointer is of type "int *" and the dereference operator operated on the //variable i in memory 1008
pointer, the result is a value of type "int"
1009
| Dereferenced pointers can be used as L-values or R-values cout << "i: " << i << endl;
1010
z When used as an L-value (on the left side of an assignment), the pointer cout << "i: " << *iPtr << endl;
is unaffected, but the memory that it points to is changed 1011
| When a pointer that is pointing to memory you are not allowed to access is *iPtr = 4; //Changes the memory being
dereferenced, the result is a program crash via a "segmentation fault" //pointed to by iPtr to contain
i: 6
//the value 4 i: 6
i: 4
cout << "i: " << i << endl; i: 4
cout << "i: " << *iPtr << endl;
COP 3330 Object Oriented Programming in C++ Lecture Slides 45/134 (c) pk
1
Arrays And Pointers Pointer Arithmetic,
| The name of an array variable in C++, without the use of the [ ] operator, represents Motivation
the starting address of the array
| Incrementing the contents of an "int
| This address can be stored in a pointer variable *" variable by one doesn't make
z Since array values are guaranteed to be in contiguous memory, you can access sense 1000 NUM 1012 iAry[2]
array values using this one pointer z Integers require 4 bytes of
3 6
1001 1013
z Examples of this will come later, after discussing "pointer arithmetic" storage 1002 1014
int iAry[NUM] = { 2, 4, 6 }; the pointer pointing to location 1004 iAry[0] 1016 iPtr
Pointer Arithmetic,
Using Pointer Arithmetic
Description 1000 NUM 1012 iAry[2]
3 6
1001 1013
| Recall that a pointer type specifies the type of value it is pointing to const int NUM = 3;
1002 1014
int iAry[NUM] = { 2, 4, 6 };
z C++ can determine the size of the value being pointed to int *iPtr; 1003 1015
int *iPtr2; 1004 iAry[0] 1016 iPtr
z When arithmetic is performed on a pointer, it is done using this knowledge to
int *iPtr3;
ensure the pointer doesn't point to intermediate memory locations int i;
1005
1006 2
1017
1018
1004
z If an int requires 4 bytes, and iPtr is a variable of type "int *", then the statement 1007 1019
iPtr = iAry; //Assigns iPtr to point
"iPtr++;" actually increments the pointer value by 4 //to the first integer
1008 iAry[1] 1020
z Similarly, "iPtr2 = iPtr + 5;" stores the address "five integers worth" past iPtr in
iPtr2
//in the iAry array 1009
1010 4 1021
1022
iPtr3 = iAry; 1011 1023
• If iPtr was 1000, then iPtr2 would contain the address 1020 for (i = 0; i < NUM; i++)
{
• 1020 = 1000 + 5 * 4 iPtr2 = iPtr + i;
| Pointer arithmetic is performed automatically when arithmetic is done on pointers cout << i << " " << 02222
iAry[i] << " " <<
z No special syntax is required to get this behavior! *iPtr2 << " " << 14444 Other
*iPtr3 << " " << 26666 Variables
*(iPtr + i) << endl;
iPtr3++;
}
Dynamic Allocation Of
Static Allocation Of Arrays
| All arrays discussed or used thus far in the course have been "statically allocated"
Arrays
z The array size was specified using a constant or literal in the code
| If an array is "dynamically allocated", then space is not reserved
z When the array comes into scope, the entire size of the array can be allocated,
for the array until the size is determined
because it was specified
z This may not be until the middle of a function body, using a
| You won't always know the array sizes when writing source code value that is not constant or literal
z Consider a program that modifies an image
z The size may be input by the user, read from a file,
z As the developer, you won't know what image size the user will use computed from other variables, etc.
z One solution: Declare the image array to be 5000 rows by 5000 columns | As memory is "claimed" using dynamic allocation, the starting
• Problem #1: This likely wastes a lot of memory – if the user uses an image address is provided, allowing it to be stored in a pointer variable
that is 250x250, then there are 24,937,500 unused pixels. If each pixel | Since pointers can be used to access array elements, arrays
requires 4 bytes, this is almost 100 MB (megabytes!) of wasted space can be dynamically allocated in this way
• Problem #2: What if the user needs to edit an image that is 6000x6000? | Dynamically allocated memory is claimed from the heap, as
Your program will fail, and likely result in a crash opposed to the stack
COP 3330 Object Oriented Programming in C++ Lecture Slides 46/134 (c) pk
2
The "new" Operator Static Vs Dynamic Allocation
| A new operator is used to perform dynamic allocation
Stack allocation
z The operator is the "new" operator
| The new operator: int intArray[10];
z Attempts to find the amount of space requested from the heap intArray[0] = 6837; Code
z "Claims" the memory when an appropriately sized available chunk of the heap is
found Heap allocation Stack
z Returns the address of the chunk that was claimed
int *intArray;
| "new" can be used to allocated individual variables: intArray = new int[10];
iPtr = new int; //allocates an int variable intArray[0] = 6837;
| "new" can also be used to allocated arrays of variables:
iPtr = new int[5]; //allocates an array of 5 integers ...
| Array elements can be accessed using pointer arithmetic and dereferencing, or via
Heap
the well-know [ ] operator, indexing an array delete[] intArray;
COP 3330 Object Oriented Programming in C++ Lecture Slides 47/134 (c) pk
3
Using The "delete" Operator Fixing The Memory Leak
| Dynamically allocated memory can be released back into the available memory store
using the "delete" operator int i; //Loop variable
int *iary; //This will be our array - an int pointer
| The delete operator operates on a pointer and frees the memory being pointed to int num; //Length of the array (input from user)
z Recall – a pointer may be pointing to a single value, or an array of values
for (i = 0; i < 100000; i++)
z Due to this, the delete operator is used differently to delete single values and
{
arrays num = 50000;
| Deleting a single value being pointed to:
delete iPtr; iary = new int[num];
| Deleting an array of values being pointed to: //Call a function to randomly fill the array
delete [] iPtr; //Do some sort of processing on the 50000 element ary
| Using the delete operator on a null pointer has no effect //Do it again and again and again, accumulating stats.
| Using the delete operator on a pointer pointing to memory that is not currently delete [] iary; //No need to tell delete the size of
claimed by your program will cause a segmentation fault //the array. This only frees up the
z Initialize all pointers to 0 (zero) //memory that iary is pointing to. It
//does NOT delete the pointer in any way
z Set all pointers to 0 after using the delete operator on them
}
...
COP 3330 Object Oriented Programming in C++ Lecture Slides 48/134 (c) pk
4
The sizeof Operator Dynamically Alloc Mem in C
| Often, you need to know how many bytes of memory a variable or type requires.
| Operators "new" and "delete" don't exist in C, but C programmers still need dynamic
| Different architectures use different sizes. allocation.
| Use the sizeof operator to determine the current architecture's size of a var or type | Three important functions for C dynamic allocation
COP 3330 Object Oriented Programming in C++ Lecture Slides 49/134 (c) pk
5
Out of memory errors Multidimensional Arrays
#include <iostream>
return 0;
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 50/134 (c) pk
6
Multi-dimensional Arrays Buffer Overflow problems
Let A be a string and B be an integer. A A A A A A A A B B
| int (*matrix)[10]; Changing A could change B!
0 0 0 0 0 0 0 0 0 3
z Pointer to an array of 10 integers
/* overflow.c - demonstrates a buffer overflow */
| int *matrix[10]; #include <stdio.h>
#include <string.h>
z Array of 10 integer pointers. int main(int argc, char *argv[]) {
char buffer[10];
z Example: if (argc < 2) {
• int main( int argc , char *argv[]) fprintf(stderr, "USAGE: %s string\n", argv[0]);
return 1;
• argv[0] = “prgram name” }
• argv[1] = “../data/filename”
• argv[2] = “2” strcpy(buffer, argv[1]);
return 0;
}
| static_cast<T>(expression)
x=(float) i; cast in C++ - C notation
The static_cast<>() is used to cast between the
x=float(i); cast in C++, functional notation integer types.
'eg' char->long, int->short etc.
x=static_cast<float>(i); ANSI C++ - recommended
| Static cast is also used to cast pointers to
i=reinterpret_cast<int>(&x) ANSI C++, not portable and system related types, for example casting void* to the
dependent
func(const_cast<int>(c_var)) where C_var is a const variable
appropriate type.
Used for removing “const-ness” when
invoking func. Use with care. BaseClass_Employee* a = new DerivedClass_Manager();
static_cast<DerivedClass_Manager>(a)->derivedClassMethod();
COP 3330 Object Oriented Programming in C++ Lecture Slides 51/134 (c) pk
7
reinterpret_cast const_cast
float f = 2.5f;
| const_cast<T>(expression)
double * pd = reinterpret_cast<double*>(&f); The const_cast<>() is used to
cout << f << endl << *pd << endl; add/remove const(ness) of a variable.
Outputs (!!!):
class A {public: void func() {} };
$ ./a.exe void f(const A& a)
2.5 {
3.50861e+159 A& b = const_cast<A&>(a);
b.func();
}
Reinterpret cast simply casts one type bitwise to another. Any pointer or integral type
can be casted to any other with reinterpret_cast, easily allowing for misuse.
static_cast will not be allowed in this case.
Implicit conversions
| char, short and bool are promoted to int
| Integer types which cannot be
represented with an int are promoted to
unsigned
| In an expression with mixed type, lower
order operand are promoted to the upper
order, with the following rule:
• int < unsigned < long
< unsigned long < float < double
< long double
| bool is an integer type, true is
promoted to 1 and false to 0
COP 3330 Object Oriented Programming in C++ Lecture Slides 52/134 (c) pk
8
GDB
GDB |
|
Lot of tutorials on google.
Debugging tool, see what happens as your
program runs
| Needs the –g flag while compiling
For : COP 3330. z This adds additional information (i.e. line
Object oriented Programming (Using C++) numbers) in the binary executable
http://www.compgeom.com/~piyush/teach/3330 | Execution:
z Invoke by typing “gdb <executable name>”
z E.g.: gdb a.out
Piyush Kumar
Basic Commands
| where/bt
z Shows the current line and stack backtrace. Very
useful for segmentation faults.
| info registers
z Shows the current state of the registers
| display <var/register>
z display the contents of the register/var.
z E.g. : display count
z display $eax
| More Commands:
z http://sources.redhat.com/gdb/onlinedocs/gdb_toc.html
| Graphical User interface: ddd
| Screen shots/movies : http://undo-software.com/undodb_screens.html
COP 3330 Object Oriented Programming in C++ Lecture Slides 53/134 (c) pk
1
Exceptions
Exceptions are run‐time anomalies, such as division by
Exceptions
•
zero, that require immediate handling when encountered
by your program. The C++ language provides built‐in
support for raising and handling exceptions. With C++
exception handling, your program can communicate
unexpected events to a higher execution context that is
better able to recover from such abnormal events.
For : COP 3330. • Useful when the code that detects the problem cannot
Object oriented Programming (Using C++) handle it (Exception‐Detection code). Control must be
transferred to the code that can handle such error.
http://www.compgeom.com/~piyush/teach/3330 (Exception‐Handling code).
Piyush Kumar
Material from “4th ed. Programming and Problem solving with C++, Dale, Weems.
COP 3330 Object Oriented Programming in C++ Lecture Slides 54/134 (c) pk
1
The try-catch Statement Example of a try-catch Statement
How one part of the program catches and processes try
{
the exception that another part of the program throws. // Statements that process personnel data and may throw
TryCatchStatement // exceptions of type int, string, and SalaryError
}
try catch ( int )
Block {
// Statements to handle an int exception
catch (FormalParameter) }
Block catch ( string s )
catch (FormalParameter) {
cout << s << endl; // Prints "Invalid customer age"
FormalParameter // More statements to handle an age error
}
DataType VariableName catch ( SalaryError )
{
// Statements to handle a salary error
… }
COP 3330 Object Oriented Programming in C++ Lecture Slides 55/134 (c) pk
2
A Solution cin >> numer >> denom;
while (cin)
{
//“quotient.cpp” -- Quotient program try
#include<iostream> {
#include <string> cout << "Their quotient: "
<< Quotient(numer, denom) << endl;
using namespace std;
}
int Quotient(int,int);
catch (DivByZero)
class DivByZero // Exception class
{
{}; cout << "*** Denominator can't be 0"
int main() << endl;
{ }
int numer; // Numerator cout << "Enter numerator and denominator: ";
COP 3330 Object Oriented Programming in C++ Lecture Slides 56/134 (c) pk
3
Functions in C++
Declarations vs Definitions
Functions |
| Inline Functions
| Class Member functions
| Overloaded Functions
For : COP 3330.
| Pointers to functions
Object oriented Programming (Using C++)
http://www.compgeom.com/~piyush/teach/3330
| Recursive functions
Piyush Kumar
Gcd Example
1071,1029
What you should know? 1029, 42
42, 21
Calling a function?
21, 0 #include <iostream>
COP 3330 Object Oriented Programming in C++ Lecture Slides 57/134 (c) pk
1
Pointer Parameters Const parameters
#include <iostream>
#include <vector>
using std::vector; | Fcn(const int i) {}…
using std::endl;
using std::cout;
z Fcn can read but not write to i.
void reset(int *ip)
{
*ip = 0; // changes the value of the object to which ip points
ip = 0; // changes only the local value of ip; the argument is unchanged
}
int main()
{
int i = 42;
int *p = &i;
COP 3330 Object Oriented Programming in C++ Lecture Slides 58/134 (c) pk
2
Array parameters No return values?
| void printvalues(const int ia[10]); | void swap (int &v1, int &v2);
z Parameter treated as “const int *”
return 0;
}
Recursion Recursion
COP 3330 Object Oriented Programming in C++ Lecture Slides 59/134 (c) pk
3
Recursion Recursion
int main() {
template <typename T> vector<int> vs;
void recSort(T begin, T end){ int N = 10;
int len = distance(begin,end);
if( len <= 1) return; for(int i = 0; i < N; ++i)
vs.push_back(rand());
for(int i = 1; i < len; ++i)
if(*(begin+i) < *(begin)) recSort(vs.begin(), vs.end());
swap( *(begin+i) , *(begin) ); for(int i = 0; i < N; ++i)
recSort(begin+1,end); cout << vs[i] << endl;
return 0;
} }
Recursion Recursion
void recSort(vector<int>::iterator begin,
template <typename T>
void recSort(T begin, T end){
vector<int>::iterator end){
int len = distance(begin,end);
| Another example.
int len = distance(begin,end);
if( len <= 1) return; void printNum(int n)
if( len <= 1) return; Generates {
for(int i = 1; i < len; ++i) for(int i = 1; i < len; ++i) if (n >= 10) printNum(n/10);
if(*(begin+i) < *(begin)) if(*(begin+i) < *(begin)) print(n%10);
swap( *(begin+i) , *(begin) ); }
swap( *(begin+i) , *(begin) );
recSort(begin+1,end);
recSort(begin+1,end); Another version.
}
}
void printNumB(int n, int b)
{
if (n >= b) printNumB(n/b);
print(n%b);
Can you see the recursion in a Sudoku solver? }
Recursion Recursion
Eight Queens problem:
|
z Brute force solution: 64^8 = 2^48 = 281,474,976,710,656 possible
| Invariants:
blind placements of eight queens,
z no two pieces can share the same row
z any solution for n queens on an n×m
board must contain a solution for n−1
queens on an (n−1)×m board
z proceeding in this way will always
keep the queens in order, and
z The eight queens puzzle is based on the problem of
generate each solution only once.
putting eight chess queens on an 8×8 chessboard such that
none of them is able to capture any other using the
standard chess queen's moves.
COP 3330 Object Oriented Programming in C++ Lecture Slides 60/134 (c) pk
4
Backtracking Eight Queens
COP 3330 Object Oriented Programming in C++ Lecture Slides 61/134 (c) pk
5
Function overloading
COP 3330 Object Oriented Programming in C++ Lecture Slides 62/134 (c) pk
6
Classes: Member functions
// classes example
#include <iostream>
Classes: Methods, Constructors, using namespace std;
int main () {
Square s;
s.set_values (3);
cout << "area: " << s.area();
Piyush Kumar return 0;
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 63/134 (c) pk
1
Assignment operator Variable assignment
| The member functions in the public | Only the public members of an object
section of a class can be accessed can be directly accessed.
using the “.” operator for instantiated
objects. (For pointers its -> )
z Square s1, *s2;
z s1.set_values(5);
z s2 = new Square; s2->set_values(10);
z delete s2;
COP 3330 Object Oriented Programming in C++ Lecture Slides 64/134 (c) pk
2
Constructors Constructors
| Differs from other member functions. | Have the same name as the class.
| Initializes a newly created object. // classes example
#include <iostream>
| Other member functions are invoked using namespace std;
int main () {
by existing objects. class Square {
Square s(3);
cout << "area: " << s.area();
int x;
| A Constructor is invoked automatically return 0;
public:
}
when an object is created. Square(int w){ x = w; };
int area () {return (x*x);};
void set_values(int a);
int get_sidelen(void) const;
};
void Square::set_values(int a){ x = a; };
int Square::get_sidelen(void) const { return x;}
| Have the same name as the class. | You can have several constructors for
class Square { int main () { a class by overloading them.
int x; Square s;
public: cout << "area: " << s.area();
return 0; class Square {
Square(){ x = 0; };
} int x;
int area () {return (x*x);};
public:
void set_values(int a);
Square(int w){ x = w; };
int get_sidelen(void) const;
Square() { x = 0; };
};
int area () {return (x*x);};
void Square::set_values(int a){ x = a; };
void set_values(int a);
int Square::get_sidelen(void) const { return x;}
int get_sidelen(void) const;
};
COP 3330 Object Oriented Programming in C++ Lecture Slides 65/134 (c) pk
3
Copy Constructors Copy constructors: When is it called?
| Gets called in a number of situations. | When the return value of a function has
class type.
| If you do not write one, the compiler z Fraction process_fraction (int i, int j);
automatically generates one for you. | When an argument has class type. A copy
of the argument is made and passed to the
function
z int numerator_process (Fraction f);
| When you use one object to initialize
another object.
z Fraction a(1,3); Fraction b(a);
| It’s only called when a new copy of an | Const: Making a copy should not alter
existing object needs to be created. source.
| &: The function should not need to call
another copy constructor!
Copy Constructors:
Destructors
Example.
class Point {
| You can have many constructors but only
int x,y; one destructor.
| The destructor must have the same name
public:
int xx(void) const { return x;}; as the class, but preceded with a tilde sign
int yy(void) const { return y;}; (~) and it must also return no value.
Point(Point const &p){
this->x = p.xx();
| The use of destructors is especially suitable
this->y = p.yy(); when an object assigns dynamic memory
}; during its lifetime and at the moment of
}; being destroyed we want to release the
memory that the object was allocated.
COP 3330 Object Oriented Programming in C++ Lecture Slides 66/134 (c) pk
4
// example on constructors and destructors (from cplusplus.com)
#include <iostream>
using namespace std;
class CRectangle {
Pointers to functions
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
| Not in syllabus.
int area () {return (*width * (*height));}
};
class CRectangle {
Assignment operators
int *width, *height;
public:
CRectangle (int,int); | int x;
~CRectangle ();
int area () {return (*width * (*height));} | x = 4;
};
| 4 = x? // non-lvalue in assignment
CRectangle::CRectangle (int a, int b) {
width = new int;
| x = y = z = 8;
height = new int; z Z is assigned 8 first
*width = a; *height = b;
} z Y is then assigned the value of returned by
(z = 8) which is 8.
CRectangle::~CRectangle () { delete width; delete height; }
int main () { z x is now assigned the value returned by (y =
CRectangle rect (3,4), rectb (5,6); 8) which is 8
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 67/134 (c) pk
5
Assignment operators Assignment operators
COP 3330 Object Oriented Programming in C++ Lecture Slides 68/134 (c) pk
6
Guidelines
| Place the common code used by the assignment
int main()
operator and the copy constructor in a separate
{ function and have each one call the function. This will
Buf myBuf( "my buffer", 10 ); make your code more compact and avoid duplication.
Buf yourBuf( "your buffer", 12 ); | A String class must copy a character string during the
copy constructor and during an assignment. If we
// Display 'my buffer' place this common code into a private member
myBuf.Display(); function
| void CopyString(const char* ptr); then both the copy
// assignment opperator
constructor and assignment operator may call this
myBuf = yourBuf;
routine to perform the copy rather than duplicate this
// Display 'your buffer'
code in each.
myBuf.Display();
}
From: http://www.acm.org/crossroads/xrds1-4/ovp.html
Guidelines Guidelines
| If your class has pointer data, you must provide an | Always implement the assignment operator
assignment operator. If writing an assignment
operator, you must also write a copy constructor. for your class; do not let the compiler
| The generated assignment operator performs generate the default assignment operator.
member-wise assignment on any data members of
your class. For pointer variables, we almost always do
| The compiler will generate a default
not want this because the data members of the copy assignment operator for your class if you do
will point to the same data as the copied object! not provide one. In order to be in complete
Worse, if one of the objects is destroyed, the data is
destroyed with it. A run-time error will occur the next control of how your class operates, always
time the remaining object tries to access the now non- provide an assignment operator.
existent data.
Guidelines Guidelines
| Check for assignment to self.
| The destructor must release any
| Disaster can result if a variable is assigned to itself.
Consider: resources obtained by an object
| X x; x = x; Suppose class X contains pointer data during its lifetime, not just those that
members that are dynamically allocated whenever an
object is created. Assignment always modifies an were obtained during construction.
existing object. The dynamic data will, therefore, be
released before assigning the new value. If we do not | Make the constructor as compact as
check for assignment to self, the above assignment possible to reduce overhead and to
will delete the existing pointer data, and then try to
copy the data that was previously deleted! minimize errors during construction.
COP 3330 Object Oriented Programming in C++ Lecture Slides 69/134 (c) pk
7
Abstraction and
Encapsulation
Classes II: Type Conversion, | Abstraction: Separation of interface
Friends, … from implementation
| Encapsulation: Combining lower level
elements to form higher-level entity.
For : COP 3330.
| Access Labels
Object oriented Programming (Using C++)
http://www.compgeom.com/~piyush/teach/3330
(public/private/protected) enforce
abstraction and encapsulation.
Piyush Kumar
Using Typedefs to
More on Class definitions
streamline classes.
COP 3330 Object Oriented Programming in C++ Lecture Slides 70/134 (c) pk
1
Class declaration for class
Class declaration
members.
| class Screen; // declaration of the class | Because a class is not defined until its
| Forward declaration: Introduces the name class body is complete, a class cannot
Screen into the program and indicates that have data members of its own type.
Screen refers to a class name.
| A class can have data members that
| Incomplete Type: After declaration, before
definition, Screen is an incomplete type. It’s
are pointers or references to its own
known screen is a type but not known what type.
class Human {
members that type contains. Screen window;
Human *bestfriend;
Human *father, *mother;
…
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 71/134 (c) pk
2
Mutable data members Guideline.
class Screen {
public:
| Never repeat code.
private:
| If you have member functions that
mutable size_t access_ctr; need to have repeated code, abstract
}; it out in another function and make
void Screen::do_display(std::ostream& os) const {
them call it (maybe inline it).
++access_ctr; // keep count of calls to any member func.
os << contents;
}
the class type. // Function that receives an object of type String as an argument
void foo( const String& aString );
Class Sales_item {
Public: // Here we call this function with an int as argument
Sales_item(const std::string &book = “ “) int x = 100; foo( x ); // Implicit conversion: foo( String( x ) );
: isbn (book), units_sold(0), revenue(0.0) {}
…
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 72/134 (c) pk
3
Use of implicit type Suppressing implicit
conversion conversions.
class String {
public:
| Use “explicit” before conversion
String( char* cp ); // Constructor constructors.
operator const char* () const;
// Conversion operator to const char*
// ...
};
explicit String( char* cp ); // Constructor
void foo( const String& aString );
void bar( const char* someChars );
// main.cc
int main() {
foo( "hello" ); // Implicit type conversion char* -> String
String peter = "pan";
bar( peter ); // Implicit type conversion String -> const char*
}
Friends. Friends
| friend function/classes
| Properties
z Can access private and protected
z Friendship is granted, not taken
(more later) members of another class
z NOT symmetric
z friend functions are not member
• if B a friend of A, A not necessarily a friend of B
functions of class
z NOT transitive
• Defined outside of class scope
• if A a friend of B, B a friend of C, A not necessarily a
z A Friend declaration begins with the friend of C.
keyword “friend”
Friends Friends
– friend declarations
z friend function | Why use friends?
• Keyword friend before function prototype in z to provide more efficient access to data
class that is giving friendship. members than the function call
– friend int myfunc( int x ); z to accommodate operator functions with
easy access to private data members
– Appears in the class granting friendship
z friend class | Be careful: Friends can have access to
• Type friend class Classname in class everything, which defeats data hiding.
granting friendship | Friends have permission to change the
• If ClassOne granting friendship to ClassTwo, internal state from outside the class. Always
friend class ClassTwo; use member functions instead of friends to
appears in ClassOne's definition change state
COP 3330 Object Oriented Programming in C++ Lecture Slides 73/134 (c) pk
4
An example
#include <iostream>
#include <string>
class Sales_item {
friend bool operator==(const Sales_item&, const Sales_item&);
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
// other members as before
public:
// added constructors to initialize from a string or an istream
Sales_item(const std::string &book):
isbn(book), units_sold(0), revenue(0.0) { }
Sales_item(std::istream &is) { is >> *this; }
public:
// operations on Sales_item objects
// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& operator+=(const Sales_item&);
// other members as before
…
COP 3330 Object Oriented Programming in C++ Lecture Slides 74/134 (c) pk
5
Sorted Arrays As Lists
Introduction to |
|
Arrays are used to store a list of values
Arrays are contained in contiguous memory
Data Structures
z Recall – inserting a new element in the middle of an array requires later elements
to be "shifted". For large lists of values, this is inefficient.
void insertSorted(int value, int &length, int list[])
{
int i = length - 1; Shifting array elements
For : COP 3330. while (list[i] > value) that come after the
Object oriented Programming (Using C++) { element being inserted
list[i + 1] = list[i];
http://www.compgeom.com/~piyush/teach/3330 i--;
} 4 8 13 29 37
list[i + 1] = value; Insert 6
length++; 4 6 8 13 29 37
}
Piyush Kumar
COP 3330 Object Oriented Programming in C++ Lecture Slides 75/134 (c) pk
1
Insertion Into Linked Lists Linked List Nodes, Example
| Given the initial linked list: • Use a class to group the value and the pointer
class ListNodeClass
2 4 6 8 10 {
public: // Only for illustration: Bad design
int val; //Will have a list of ints
ListNodeClass *next; //Point to the next node
};
Insert node with value 5
int main()
{
2 4 6 8 10 ListNodeClass *head = 0; //Essentially, this declares a
//list, since it will point to the
5 //first node of a list. Initially,
//list is empty (null pointer)
Resulting in
head = new ListNodeClass; //Note no [] - not
//declaring an array - just
2 4 5 6 8 10 //one single node
...
COP 3330 Object Oriented Programming in C++ Lecture Slides 76/134 (c) pk
2
Deleting From Front Of List Searching A List
int main(void)
{
bool deleteFromFront( ListNodeClass *head = 0; bool searchList(ListNodeClass *head, int val)
ListNodeClass **head) printList(head); {
{ insertAtHead(&head, 5); bool found = false;
bool status = true; insertAtHead(&head, 8);
ListNodeClass *temp; insertAtHead(&head, 17); ListNodeClass *temp = head;
printList(head);
if (*head == 0) deleteFromFront(&head); while (temp != 0 && !found)
{ printList(head);
deleteFromFront(&head);
{
cout << "Can't delete from list"
<< endl; deleteFromFront(&head); if (temp->val == val)
status = false; printList(head); {
} deleteFromFront(&head); found = true;
else return (0);
{ } }
temp = *head; else
*head = temp->next; List is Empty! {
//Free the memory we dynamically 17 8 5 temp = temp->next;
//allocated in insert function
delete temp; 85 }
} List is Empty! }
return (status); return (found);
}
Cannot delete from list!
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 77/134 (c) pk
3
The Priority Queue Linked
The Doubly-Linked List Structure
Structure | The linked list examples we've seen so far have only one
pointer
| A priority queue works slightly differently than a "normal" queue
| Often, it may be advantageous to have a node contain multiple
| Elements in a priority queue are sorted based on a priority "head" pointers "tail"
z Queue order is not dependent on the order in which
2 4 6 8
elements were inserted, as it was for a normal queue
z As elements are inserted, they are sorted such that the class DoublyLinkedListNodeClass
element with the highest priority is at the beginning of the {
priority queue DoublyLinkedListNodeClass *prev;
z When an element is removed from the priority queue, the int val;
first element (highest priority) is taken, regardless of when it DoublyLinkedListNodeClass *next;
was inserted
};
z Elements of the same priority are maintained in the order
which they were inserted
DoublyLinkedListNodeClass *head;
| Using a priority queue in which all elements have the same DoublyLinkedListNodeClass *tail;
priority is equivalent to using a "normal" queue
http://www.sgi.com/tech/stl/List.html
Note that singly linked lists, which only support forward traversal,
are also sometimes useful. If you do not need backward traversal,
then slist may be more efficient than list.
COP 3330 Object Oriented Programming in C++ Lecture Slides 78/134 (c) pk
4
Stack Example. Simpler Stack example
// C++ STL Headers
#include <iostream> int main() {
#include <vector> stack<int> S;
#include <stack>
S.push(8);
int main( int argc, char *argv[] ) S.push(7);
{ S.push(4);
stack<const char *, vector<const char *> > s; assert(S.size() == 3);
// Push on stack in reverse order
s.push("order"); assert(S.top() == 4);
s.push("correct"); // Oh no it isn't ! S.pop();
s.push("the");
s.push("in");
s.push("is"); assert(S.top() == 7);
s.push("This"); S.pop();
// Pop off stack which reverses the push() order
while ( !s.empty() ) { assert(S.top() == 8);
cout << s.top() <<" "; s.pop(); /// Oh yes it is ! S.pop();
}
cout << endl;
assert(S.empty());
return( EXIT_SUCCESS ); }
} ©Phil Ottewell's STL Tutorial http://www.sgi.com/tech/stl/stack.html
#include <queue>
#include <vector>
int main() {
priority_queue<int> Q;
Q.push(1);
Q.push(4);
Q.push(2);
Q.push(8);
Q.push(5);
Q.push(7);
assert(Q.size() == 6);
assert(Q.top() == 8);
Q.pop();
Graphs
assert(Q.top() == 7);
Q.pop();
assert(Q.top() == 5);
Q.pop();
assert(Q.top() == 4);
An introduction
Q.pop();
assert(Q.top() == 2);
Q.pop();
assert(Q.top() == 1);
Q.pop();
assert(Q.empty());
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 79/134 (c) pk
5
Graphs Directed graph
COP 3330 Object Oriented Programming in C++ Lecture Slides 80/134 (c) pk
6
World Wide Web 9-11 Terrorist Network
| Social network graph.
| Web graph. z Node: people.
z Node: web page. z Edge: relationship between
z Edge: hyperlink from one page to another. two people.
cnn.com
hbo.com
sorpranos.com
a b
Reference: http://www.twingroves.district96.k12.il.us/Wetlands/Salamander/SalGraphics/salfoodweb.giff
Terminology Question
| A Simple Graph is a graph with no self | Max Degree node? Min Degree
loops or parallel edges. Node? Isolated Nodes? Total sum of
| Incidence: v is incident to e if v is an degrees over all vertices? Number of
end vertex of e. edges?
e
v
COP 3330 Object Oriented Programming in C++ Lecture Slides 81/134 (c) pk
7
QUESTION Connected graph
| How many edges are there in a graph | Undirected Graphs: If there is at least
with 100 vertices each of degree 4? one path between every pair of
vertices. (otherwise disconnected)
n(n-1)/2 edges
Representing Graphs
representation 1 1
4
2 2
4
| Two ways
z Adjacency List 3 3
• ( as a linked list for each node in the
Adjacent Initial Terminal
graph to represent the edges) |Vertex
Vertices Vertex Vertices
z Adjacency Matrix
1 2, 3, 4 1 3
• (as a boolean matrix)
2 1, 4 2 1
3 1, 4 3
4 1, 2, 3 4 1, 2, 3
COP 3330 Object Oriented Programming in C++ Lecture Slides 82/134 (c) pk
8
adjacency list adjacency matrix
Another example AL Vs AM
AL Vs AM
COP 3330 Object Oriented Programming in C++ Lecture Slides 83/134 (c) pk
9
The problem Other Similar problems
| There are n men and n women | Given a set of colleges and students pair
them. (Internship – Company assignments)
| Each man has a preference list, so does the
| Given airlines and pilots, pair them.
woman.
| Given two images, pair the points belonging
| These lists have no ties. to the same point in 3D to extract depth
from the two images.
| Dorm room assignments.
| Devise a system by which each of the n
| Hospital residency assignments**.
men and n women can end up getting
| Your first programming assignment…
married.
st nd rd st nd rd
Man 1 2 3 Woman 1 2 3
X A B C A Y X Z
Y B A C B X Y Z
Z A B C C X Y Z
st nd rd st nd rd st nd rd st nd rd
Man 1 2 3 Woman 1 2 3 Man 1 2 3 Woman 1 2 3
X A B C A Y X Z X A B C A Y X Z
Y B A C B X Y Z Y B A C B X Y Z
Z A B C C X Y Z Z A B C C X Y Z
COP 3330 Object Oriented Programming in C++ Lecture Slides 84/134 (c) pk
10
Stability is Primary. Main Idea
Men Propose
(Women dispose)
Initialize each person to be free.
while (some man m is free and hasn't proposed to every woman)
w = first woman on m's list to whom m has not yet proposed
if (w is free)
assign m and w to be engaged
else if (w prefers m to her fiancé m')
assign m and w to be engaged, and m' to be free
else
w rejects m
COP 3330 Object Oriented Programming in C++ Lecture Slides 85/134 (c) pk
11
Operator overloading
Operator C++ allows overloading of most of the standard operators. We are
allowed to define standard operators for new types.
For : COP 3330. Suppose we have a class MyNum, a new numerical type.
z The syntax for defining operators is
Object oriented Programming (Using C++) z ReturnType operator@(argument list…)
http://www.compgeom.com/~piyush/teach/3330 z For example:
Piyush Kumar
Example Example
class MyNum { class MyNum {
public: public:
... ...
}; };
| Here are a few of the many examples of operator | Operator overloading makes life
overloading: easier for the users of a class, not for
z myString + yourString might concatenate two the developer of the class!
std::string objects
z myDate++ might increment a Date object | Supports more natural usage.
COP 3330 Object Oriented Programming in C++ Lecture Slides 86/134 (c) pk
1
Operator Overloading:
Precedence of Operators
Another example
class Array {
public:
class Array {
public:
| Ival = jval = kval = lval
int& elem(unsigned i)
{ if (i > 99) error(); return data[i]; }
int& operator[] (unsigned i)
{ if (i > 99) error(); return data[i]; } z Right associative
private: private:
int data[100]; int data[100]; z (Ival = (jval = (kval = lval)))
}; };
COP 3330 Object Oriented Programming in C++ Lecture Slides 87/134 (c) pk
2
Class member Vs
Operator Overloading
non-member
Operators can be global or member. As a member function, the first operand
| Which ones should you override? becomes its object, that is, “*this”.
| Substraction operator as a friend/global :
z The ones your user wants you to. Do MyNum operator-(const MyNum & a, const MyNum & b);
not confuse your users. | As a member of class MyNum:
COP 3330 Object Oriented Programming in C++ Lecture Slides 88/134 (c) pk
3
Guideline: Guideline vector ,deque ,list ,slist
COP 3330 Object Oriented Programming in C++ Lecture Slides 89/134 (c) pk
4
IO operators:
Output Operators
Always Non-Member
| Generally, output operators print the | // if operator<< is a member of Sales_item
contents of the object with minimal z Sales_item item; item << cout;
formatting. They should not print a | The usage is the opposite of normal way we
newline. use output operators.
COP 3330 Object Oriented Programming in C++ Lecture Slides 90/134 (c) pk
5
Operator< and sorting Operator< and Sorting
// Set up vectors
vector<associate> v(arr, arr+20), v1((size_t)20),
int main () v2((size_t)20);
{
vector<associate>::iterator i, j, k; // Copy original vector to vectors #1 and #2
bool operator<(const associate &x, const associate &y)
copy(v.begin(), v.end(), v1.begin());
{ associate arr[20] = copy(v.begin(), v.end(), v2.begin());
return x.num < y.num; {associate(-4, ' '), associate(16, ' '),
} associate(17, ' '), associate(-3, 's'), // Sort vector #1
associate(14, ' '), associate(-6, ' '), sort(v1.begin(), v1.end());
associate(-1, ' '), associate(-3, 't'),
ostream& operator<<(ostream &s, const associate &x)
associate(23, ' '), associate(-3, 'a'), // Stable sort vector #2
{ associate(-2, ' '), associate(-7, ' '),
return s << "<" << x.num << ";" << x.chr << ">"; stable_sort(v2.begin(), v2.end());
associate(-3, 'b'), associate(-8, ' '),
} associate(11, ' '), associate(-3, 'l'), // Display the results
associate(15, ' '), associate(-5, ' '), cout << "Original sort stable_sort" << endl;
associate(-3, 'e'), associate(15, ' ')}; for(i = v.begin(), j = v1.begin(), k = v2.begin();
i != v.end(); i++, j++, k++)
cout << *i << " " << *j << " " << *k << endl;
return 0;
}
Output :
Original sort stable_sort
<-4; >
<16; >
<-8; >
<-7; >
<-8; >
<-7; >
Subscript operator
<17; > <-6; > <-6; >
<-3;s> <-5; > <-5; >
<14; > <-4; > <-4; >
<-6; > <-3;e> <-3;s>
| Must be a member-function
<-1; > <-3;s> <-3;t>
<-3;t> <-3;l> <-3;a>
| Ordinarily, a class that defines
<23; > <-3;t> <-3;b> subscript, defines two versions.
<-3;a> <-3;b> <-3;l>
<-2; > <-3;a> <-3;e> z A nonconst member returning a
<-7; > <-2; > <-2; >
<-3;b> <-1; > <-1; >
reference.
<-8; > <11; > <11; >
z A const member returning a const
<11; > <14; > <14; >
<-3;l> <15; > <15; > reference.
<15; > <15; > <15; >
<-5; > <16; > <16; >
<-3;e> <17; > <17; >
<15; > <23; > <23; >
Example Example
#include <vector>
using std::vector; int& Foo::operator[](const size_t index)
#include <iostream> {
using std::cout; using std::endl; return data[index]; // no range checking on index
}
class Foo {
public: const int& Foo::operator[](const size_t index) const
Foo(): data(100) { for (int i = 0; i != 100; ++i) data[i] = i; } {
int &operator[](const size_t); return data[index]; // no range checking on index
const int &operator[](const size_t) const; }
// other interface members
private: int main() {
vector<int> data; Foo f;
// other member data and private utility functions
}; cout << f[50] << endl;
return 0;
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 91/134 (c) pk
6
Increment and Decrement Increment and Decrement
operators operator
// postfix: increment/decrement object but return unchanged value
// increment and decrement CheckedPtr CheckedPtr::operator++(int)
{
// no check needed here, the call to prefix increment will do the check
CheckedPtr operator++(int); // postfix operators CheckedPtr ret(*this); // save current value
CheckedPtr operator--(int); ++*this; // advance one element, checking the increment
return ret; // return saved state
}
CheckedPtr& operator++(); // prefix operators
CheckedPtr& operator--(); // prefix: return reference to incremented/decremented object
CheckedPtr& CheckedPtr::operator++()
{
if (curr == end)
throw out_of_range
("increment past the end of CheckedPtr");
Calling prefix/postfix
++ / --
operators explicitly
| Advice: Make them member functions. Mytype.operator++(0); // postfix
| For consistency, Mytype.operator++(); // prefix
z Prefix operations should return a
reference to the
incremented/decremented object
z Postfix operations should return the
“old” value (and not the reference)
COP 3330 Object Oriented Programming in C++ Lecture Slides 92/134 (c) pk
7
Function Objects Template Function Objects
struct adder {
double sum;
adder() : sum(0) {};
void operator()(double x) { sum += x; } vector<int> V(100);
}; generate(V.begin(), V.end(), rand);
vector<double> V;
...
adder result = for_each(V.begin(), V.end(), adder());
cout << "The sum is " << result.sum << endl;
COP 3330 Object Oriented Programming in C++ Lecture Slides 93/134 (c) pk
8
A slight deviation STL FOs
// print.hpp | #include <functional>
#include <iostream>
| Types of function objects.
template <class T> z Arithmetic FOs:
inline void PRINT_ELEMENTS( • plus<Type>, minus<type>, multiplies<type>,
const T& collection, const char * optcstr = “” ) { divides<type>, modulus<type>, negate<type>
z Relational FOs:
typename T::const_iterator pos; • equal_to<Type>, not_equal_to<type>,
std::cout << optcstr; greater<type>, greater_equal<type>, less<type>,
for ( pos = collection.begin(); pos != collection.end(); ++pos) less_equal<type>
std::cout << *pos << ‘ ‘ ; z Logical FOs:
std::cout << std::endl;
• logical_and<type>, logical_or<type>,
} logical_not<type>
COP 3330 Object Oriented Programming in C++ Lecture Slides 94/134 (c) pk
9
Function Adaptors Example (FAs n FOs)
#include <functional>
| Negators: using std::plus; using std::negate;
COP 3330 Object Oriented Programming in C++ Lecture Slides 95/134 (c) pk
10
Make FOs adaptable. Make FOs adaptable.
list<Widget *> widgetPtrs; list<Widget *> widgetPtrs;
class isOfInterest { class isOfInterest : public unary_predicate<Widget *,bool> {
public: public:
bool operator()( const Widget * pw) const; bool operator()( const Widget * pw) const;
} }
list<Widget *>::iterator foundit = find_if ( widgetPtrs.begin(), list<Widget *>::iterator foundit = find_if ( widgetPtrs.begin(),
widgetPtrs.end(), widgetPtrs.end(),
not1(isInteresting)); // ERROR not1(isInteresting));
If ( foundit != widgetPtrs.end() ) { // found what I was looking for. If ( foundit != widgetPtrs.end() ) { // found what I was looking for.
} }
COP 3330 Object Oriented Programming in C++ Lecture Slides 96/134 (c) pk
11
Conversion operators Conversion operators
template<class T> template<class T>
class Array { class Array {
public: public:
Array (int lb, int hb); Array (int lb, int hb);
Array (int size); Array (int size);
T& operator[] (int index); T& operator[] (int index);
… …
} }
bool operator==(const Array<int>& lhs, const Array<int>& rhs); bool operator==(const Array<int>& lhs, const Array<int>& rhs);
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
if ( a == b[i] ) … if ( a == b[i] ) …
Converted to : if (a == static_cast< Array<int> > (b(i)) …!!
| Design function objects for pass-by- | Only one class-type conversion is applied
value by the compiler. (else, compile time error)
| Used carefully, class-type conversions can
Template< class InputIterator, class Function > greatly simplify code. Used too freely, they
Function for_each(InputIterator first, InputIterator last,
Function f); can lead to mysterious errors.
COP 3330 Object Oriented Programming in C++ Lecture Slides 97/134 (c) pk
12
OOP
Object Oriented Object 3
Programming Object 2
Object 1
Object 4
For : COP 3330.
Object oriented Programming (Using C++)
http://www.compgeom.com/~piyush/teach/3330 Objects: State (fields), Behavior (member functions), Identity
Class : Blue print of an object.
Inheritance Inheritance
COP 3330 Object Oriented Programming in C++ Lecture Slides 98/134 (c) pk
1
Reuse Manager
| We have done unnecessary work to create class Manager : public Employee { // is a relationship
Manager, which is similar to (and really is a public:
“is a") Employee. Manager(string theName, float PayRate, int n);
| We can fix this using the OO concept of void set_manages(int n);
protected:
inheritance. int manages_n_employees;
| We let a manager inherit from an employee. };
z A manager gets all the data and functionality
of an employee after inheritance. Methods of Manager have access to name, payrate because they were
z We can then add any new data and methods declared in Employee as "protected” .
needed for a manager and redefine any
methods that differ for a manager.
More on Inheritance :
Inheritance
Access privileges.
| In a public inheritance: | Derive a new class (subclass) from an
z Public members are accessible to existing class (base class).
derived class. z Syntax:
z Protected members are accessible to • class classname : access-label base-class { … }
• Access-labels = { public, private, protected }
derived class. These members are not
accessible to the users of the base
class.
| Inheritance creates a hierarchy of
related classes (types) which share
z But private are not.
code and interface.
“Is a” relationships.
COP 3330 Object Oriented Programming in C++ Lecture Slides 99/134 (c) pk
2
Inheritance: Subclass Inheritance
COP 3330 Object Oriented Programming in C++ Lecture Slides 100/134 (c) pk
3
Example : Open-Closed Pr. More on Inheritance
Queue TestQueue
| A pointer to a derived class can
always be used as a pointer to a base
Client (Composition) class when public inheritance is used.
(But not vice-versa)
Subclass (Inheritance) z Private base classes are different
| STL Containers which need to contain
both base/derived classes should be
DeltaBoundedQueue TestBoundedQueue made of pointers to base classes.
z Otherwise : Slicing problem.
| Allows invocation of general methods | Static Binding: The compiler uses the
using a base class pointer. type of the pointer to find out which
| The fact that a reference or pointer method to call.
might refer to either a base or derived- | Dynamic Binding: The decision is
class object is the key to dynamic made at runtime. (uses ‘virtual’
binding. keyword)
| Allows easy extensibility.
COP 3330 Object Oriented Programming in C++ Lecture Slides 101/134 (c) pk
4
Dynamic Vs Static Binding Dynamic Vs Static Binding
COP 3330 Object Oriented Programming in C++ Lecture Slides 102/134 (c) pk
5
“Is a” Vs “Has a” OOP Shape Example
Inheritance
Considered an “Is a” class relationship shape
e.g.: An HourlyEmployee “is a” Employee
A Convertible “is a” Automobile
rectangle
A class contains objects of another class
as it’s member data circle ••••
triangle
Considered a “Has a” class relationship
e.g.: One class “has a” object of another
class as it’s data
COP 3330 Object Oriented Programming in C++ Lecture Slides 103/134 (c) pk
6
OOP components
Piyush Kumar
UML
“Is a” Vs “Has a” Another Example
Vehicle
COP 3330 Object Oriented Programming in C++ Lecture Slides 104/134 (c) pk
1
Pure virtual member
Pure virtual.
functions.
| A pure virtual member function is a | Specified by writing =0 after the
member function that the base class function parameter list.
forces derived classes to provide.
| A pure virtual function makes a class
an abstract base class (ABC)
z Can not be instantiated!
| An ABC can also have a pure virtual
destructor.
private:
Point2d vertices[3];
};
COP 3330 Object Oriented Programming in C++ Lecture Slides 105/134 (c) pk
2
Typecasts Containers and Inheritance
Questions Inheritance
COP 3330 Object Oriented Programming in C++ Lecture Slides 106/134 (c) pk
3
Polymorphism Polymorphism.
| Literal meaning : “Many forms” | C++ supports several kinds of static (compile-
time) and dynamic (run-time) polymorphism.
| We can use the “many forms” of z Static Polymorphism
derived and base classes • Function/Operator Overloading
interchangeably. • Class/function templates
| The fact that static and dynamic types z Dynamic polymorphism
of references and pointers can differ is • Polymorphism through inheritance/Virtual
the cornerstone of how C++ supports member functions
polymorphism.
class Swan : public Bird // Swan derives from Bird class derived : public base {
{ public:
public: virtual ~derived(){}
void OutputName() {std::cout << "a swan";} // overrides virtual function
int compare (derived &ref);
};
};
int main()
{ int my_comparison_method_for_generic_sort (base &ref1, base &ref2)
Bird* myBird = new Swan; // Declares a pointer to a generic Bird, {
// and sets it pointing to a newly-created Swan. derived & d = dynamic_cast<derived &>(ref1); // rtti used here
myBird->OutputName(); // This will output "a swan", not "a bird". // rtti enables the process to throw a bad_cast exception
delete myBird;
// if the cast is not successful
return 0;
} return d.compare (dynamic_cast<derived &>(ref2));
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 107/134 (c) pk
4
Inheritance Inheritance and templates.
public:
virtual ~BigNumber();
BigInteger BigRational
}
COP 3330 Object Oriented Programming in C++ Lecture Slides 108/134 (c) pk
5
Your library should … Graph libraries
Next homework: BFS on Graphs. Start designing your graph data structure class
in C++. You need to submit the spec sheet in the beginning of class on Nov 14th.
COP 3330 Object Oriented Programming in C++ Lecture Slides 109/134 (c) pk
6
Contents
COP 3330 Object Oriented Programming in C++ Lecture Slides 110/134 (c) pk
1
Attributes of good tests/benchmark
COP 3330 Object Oriented Programming in C++ Lecture Slides 111/134 (c) pk
2
Optimizing Compiler : choosing Optimizing Compiler’s effect
optimization flags combination
System-wide Yes, profiles all app, drivers, OS functions Just application and
Gprof
profiling instrumented DLLs
man gcov/gprof/prof
COP 3330 Object Oriented Programming in C++ Lecture Slides 112/134 (c) pk
3
Using gprof GNU profiler
COP 3330 Object Oriented Programming in C++ Lecture Slides 113/134 (c) pk
4
Flat profile: Self seconds
Flat profile: Calls
Number of seconds accounted
for this function alone Number of times
was invoked
Flat profile: Self seconds per call Flat profile: Total seconds per call
Average number of sec per call Average number of seconds spent
Spent in this function alone in this function and its descendents
per call
Descendants:
Current doit ( ) Percentage of the `total‘ total amount of
Function: time spent in this function time spent in
and its children. this function
g( )
Profiling Tools 29 Profiling Tools 30
COP 3330 Object Oriented Programming in C++ Lecture Slides 114/134 (c) pk
5
Call Graph : parents numbers Call Graph : “children” numbers
Call Graph : understanding each line total number of times the called the child `/‘
function was called total number of times this
Time that was propagated child was called
directly from the function
into this parent Current Current
Function: Function:
g( ) g( )
Memcheck is memory debugger When a program is run under Memcheck's supervision, all reads and
writes of memory are checked, and calls to malloc/new/free/delete are
detects memory-management problems intercepted
Cachegrind is a cache profiler Memcheck can detect:
performs detailed simulation of the I1, D1 and L2 caches in Use of uninitialised memory
your CPU Reading/writing memory after it has been free'd
Reading/writing off the end of malloc'd blocks
Massif is a heap profiler Reading/writing inappropriate areas on the stack
performs detailed heap profiling by taking regular Memory leaks -- where pointers to malloc'd blocks are lost forever
snapshots of a program's heap Passing of uninitialised and/or unaddressible memory to system calls
Mismatched use of malloc/new/new [] vs free/delete/delete []
Helgrind is a thread debugger Overlapping src and dst pointers in memcpy() and related functions
Some misuses of the POSIX pthreads API
finds data races in multithreaded
programs
COP 3330 Object Oriented Programming in C++ Lecture Slides 115/134 (c) pk
6
Memcheck Example Memcheck Example (Cont.)
Access of
unallocated
memory Compile the program with –g flag:
g++ -c a.cc –g –o a.out Debug
leaks
Using non-
initialized
value Execute valgrind :
valgrind --tool=memcheck --leak-check=yes a.out > log
Executable
Memory Using “free” of
leak memory allocated View log name
by “new”
Profiling Tools 37 Profiling Tools 38
S
T
A
C
K
COP 3330 Object Oriented Programming in C++ Lecture Slides 116/134 (c) pk
7
Cachegrind Summary output Cachegrind Summary output
D-cache reads
(memory reads) Data caches
I-cache reads D1 cache read misses READ performance
(instructions executed) I1 cache read misses
Instruction caches
performance
L2-cache data
L2-cache instruction read misses
read misses
COP 3330 Object Oriented Programming in C++ Lecture Slides 117/134 (c) pk
8
Spacetime Graphs Spacetime Graph (Cont.)
The dynamic linker allows each .so in the process image to have an
initialization function which is run before main(). It also allows each .so
to have a finalization function run after main() exits
COP 3330 Object Oriented Programming in C++ Lecture Slides 118/134 (c) pk
9
Writing Fast Programs CPU Architecture (Pentium 4)
COP 3330 Object Oriented Programming in C++ Lecture Slides 119/134 (c) pk
10
References
Profiling Tools 61
COP 3330 Object Oriented Programming in C++ Lecture Slides 120/134 (c) pk
11
Templates
An introduction to Are C macros on Steroids
C++ Templates Give you the power to parametrize
Compile time computation
For : COP 3330. Performance
Object oriented Programming (Using C++)
http://www.compgeom.com/~piyush/teach/3330
“The art of programming programs
that read, transform, or write other programs.”
- François-René Rideau
Piyush Kumar
COP 3330 Object Oriented Programming in C++ Lecture Slides 121/134 (c) pk
1
Templates Defining the template
min.hpp
Help us to write code without being
template <typename T>
tied to particular type. inline T const& min (T const& a, T const& b){
return a < b ? a : b ;
Question: How do you swap two }
elements of any type? How do you
return the square of any type?
Template parameter T.
Syntax: template < comma separated list of parameters >
For historical reasons, you can use “class” instead of
typename.
inline int const& min(int const& a, int const& b){ // The following does not provide operator<
return a < b ? a : b; std::complex<float> c1,c2;
#include <iostream> }
#include <string>
#include “min.hpp” …
COP 3330 Object Oriented Programming in C++ Lecture Slides 122/134 (c) pk
2
Argument deduction Template Parameters.
template <typename T> // T is a template parameter You may have as many template
inline T const& min (T const& a, T const& b){ // a and b are call parameter.
return a < b ? a : b ; parameters as you like.
}
Function Template
Template parameters.
Specialization
template <typename T1, typename T2 , typename RT > template<>
inline RT min (T1 const& a, T2 const& b){
return static_cast<RT>(a < b ? a : b); void swap<myclass>( myclass& a,
}
myclass& b){
min<int,double,double>(4,4.2); // ok: but long and tedious
a = b = 0;
template < typename RT, typename T1, typename T2 > }
inline RT min (T1 const& a, T2 const& b){
return static_cast<RT>(a < b ? a : b);
} Custom version of a template for a specific class
COP 3330 Object Oriented Programming in C++ Lecture Slides 123/134 (c) pk
3
Friend templates Member templates.
template<typename NumType, unsigned D> template <typename T>
class dpoint { class Stack {
public: private:
template<typename NT, unsigned __DIM> std::deque<T> elems; // elements
friend bool operator!= (const dpoint<NT,__DIM>& p,
const dpoint<NT,__DIM>& q); public:
void push(const T&); // store new top element
}
void pop(); // remove top element
template<typename NT, unsigned __DIM> T top() const; // return top element
bool operator!= (const dpoint<NT,__DIM>& p, bool empty() const { // return whether the stack is empty
const dpoint<NT,__DIM>& q){ return elems.empty();
//… }
}
// assign stack of elements of type T2
template <typename T2>
Stack<T>& operator= (Stack<T2> const&);
};
COP 3330 Object Oriented Programming in C++ Lecture Slides 124/134 (c) pk
4
Class Templates: Unlike
Using Specializations
function templates
Class template arguments can’t be deduced in the First declare (and/or define) the general case:
same way, so usually written explicitly: template< class T >
dpoint <double, 2> c; // 2d point class C { /* handle most types this way */ };
Class template parameters may have default values: Then provide either or both kinds of special cases as
template< class T, class U = int > desired:
class MyCls { … }; template< class T >
class C< T * > { /* handle pointers specially */ };
Class templates may be partially specialized:
template<> // note: fully specialized
template< class U > class C< int * > { /* treat int pointers thusly */ };
class MyCls< bool, U > { … }; Compiler will select the most specialized applicable
class template
Template Template
More Templates
Parameters
A class template can be a template argument
Example: template<unsigned u>
template<
template<typename ELEM> class Bag class MyClass {
>
class C { // … enum { X = u };
Bag< float > b;
};
Or even:
};
template< class E,
template<typename ELEM> class Bag
>
class C { // … Cout << MyClass<2>::X << endl;
Bag< E > b;
};
int w = Factorial<10>::value;
COP 3330 Object Oriented Programming in C++ Lecture Slides 125/134 (c) pk
5
Template Metaprograms Food for thought
template< typename NumType, unsigned D, unsigned I > struct origin
{
static inline void eval( dpoint<NumType,D>& p )
You can implement
{
p[I] = 0.0;
origin< NumType, D, I-1 >::eval( p ); IF
}
};
WHILE
// Partial Template Specialization
template <typename NumType, unsigned D> struct origin<NumType, D, 0> FOR
{
static inline void eval( dpoint<NumType,D>& p )
{
p[0] = 0.0;
Using metaprogramming. And then use
};
}
them in your code that needs to run at
compile time ☺
Learn and use the Boost MTL Library. Operate on “types” instead of data
How do you implement a “mean”
class without specifying the types.
For double arrays it should output
double
For integers it should return a float
For complex numbers it should return
a complex number
COP 3330 Object Oriented Programming in C++ Lecture Slides 126/134 (c) pk
6
Traits Traits
Template< typename T >
struct average_traits{
typedef T T_average; average_type(T) = T
};
average_type(int) = float
Template<>
struct average_traits<int>{
typedef float T;
}
Traits Sources
COP 3330 Object Oriented Programming in C++ Lecture Slides 127/134 (c) pk
7
The user.
Advanced C++
#define private public
#define protected public
For : COP 3330.
#define class struct
Object oriented Programming (Using C++)
http://www.compgeom.com/~piyush/teach/3330
Revision.
an user that willingly tries to get // the pointer, the data it refers to
around the protection mechanism // ---------------------------------------
int* p; // non-const non-const
int* const q; // const non-const
const int* r; // non-const const
const int* const s; // const const
struct A { struct C {
const int i; // hidden parameter: T* const this;
A() : i(42) {} void foo();
}; // hidden parameter: const T* const this;
void bar() const;
};
COP 3330 Object Oriented Programming in C++ Lecture Slides 128/134 (c) pk
1
Make Temporary Return Objects in Make Temporary Return Objects in
C++ Classes Const C++ Classes Const
L-values: can be used for the left side Thus, we cannot write:
of an assignment, they are non-const. int i; i++ ++; // second ++ forbidden!
R-values: cannot be used for the left Or i++++;
Error: error.cpp:5: error: non-lvalue in increment
side of an assignment. . They are
const. But:
struct A {
For example the post-increment
A operator++ (int); // the post increment operator
operator requires an l-value, but is };
itself an r-value. Now, lets try: A a; a++++; //compiles!
COP 3330 Object Oriented Programming in C++ Lecture Slides 129/134 (c) pk
2
Dynamic Polymorphism
Static Polymorphism
Example #include "coord.hpp"
COP 3330 Object Oriented Programming in C++ Lecture Slides 130/134 (c) pk
3
CRTP CRTP: Alternative outline.
Who is my
parent?
// The Curiously Recurring Template Pattern // The Curiously Recurring Template Pattern
// (CRTP) // (CRTP)
}; };
// copy constructor
}; ObjectCounter (ObjectCounter<CountedType> const&) {
++count;
}
public:
// return number of existing objects:
}; static size_t live() {
return count;
}
};
COP 3330 Object Oriented Programming in C++ Lecture Slides 131/134 (c) pk
4
Another CRTP application Another CRTP application
COP 3330 Object Oriented Programming in C++ Lecture Slides 132/134 (c) pk
5
Proxy Classes Proxy Classes
Double Dispatch
COP 3330 Object Oriented Programming in C++ Lecture Slides 133/134 (c) pk
6
Smart Pointers: auto_ptr Smart Pointers: auto_ptr
Source of trouble!
COP 3330 Object Oriented Programming in C++ Lecture Slides 134/134 (c) pk
7