C++ Mini-Course: - Part 5: Inheritance - Part 6: Libraries - Part 7: Conclusion
C++ Mini-Course: - Part 5: Inheritance - Part 6: Libraries - Part 7: Conclusion
•Part 5: Inheritance
•Part 6: Libraries
•Part 7: Conclusion
Part 5: Inheritance
How does inheritance work?
DottedSegment
must include parent publicly inherits from
header file Segment
#include “Segment.h”
class DottedSegment : public Segment
{
// DottedSegment declaration
};
virtual
• In Java every method invocation is dynamically
bound, meaning for every method invocation the
program checks if a sub-class has overridden
the method. You can disable this (somewhat) by
using the keyword “final” in Java
• In C++ you have to declare the method virtual if
you want this functionality. (So, “virtual” is the
same thing as “not final”)
• Just like you rarely say things are final in Java,
you should rarely not say things are virtual in
C++
pure virtual functions
• In Java, the “abstract” keyword means the
function is undefined in the superclass.
• In C++, we use pure virtual functions:
– virtual int mustRedfineMe(char *str) = 0;
– This function must be implemented in a
subclass.
Resolving functions
In Java: In C++:
//constructor //constructor
public Subclass(){ public Subclass() :
super(); Superclass()
} { }
virtual
• Basic advice: for now make every method
virtual except the constructor
• Make you declare your destructors virtual;
if you do not declare a destructor a non-
virtual one will be defined for you
Segment();
virtual ~Segment();
this is important
C++ Mini-Course
Part 6: Libraries
Namespaces
• Namespaces are kind of like packages in
Java
• Reduces naming conflicts
• Most standard C++ routines and classes
and under the std namespace
– Any standard C routines (malloc, printf, etc.)
are defined in the global namespace because
C doesn’t have namespaces
using namespace
#include <iostream>
...
std::string question =
“How do I prevent RSI?”;
std::cout << question << std::endl;
PointVector v;
v.push_back(Point(3, 5));
PointVectorIter iter;
for(iter = v.begin(); iter != v.end(); ++iter){
Point &curPoint = *iter;
}
C++ Mini-Course
Part 7: Conclusion
Other Resources
• The Java To C++ tutorial on the website is
probably your best source of information
• The big thick book by Stroustrop in the
back of the Sun Lab is the ultimate C++
reference
• A CS 123 TA, or specifically your mentor
TA if you have been assigned one
Question and Answer
Session