Before You Start
They can, and you've already seen examples of these, such as
HashSet<int>andTreeSet<int>both providinginsert()andexists().TreeSet<T>andIntListprovidingbegin()andend().- Lots of our classes providing
printToStream().
Hay, wait a minute! If we say
mySet.exists(42), how does the compiler know whether to callHashSet<int>::existsorTreeSet<int>::exists?
Good question! Let's ask the students!
Our program probably looks something like
TreeSet<int> mySet;
// ... more code ...
std::cout << mySet.exists(42);
Notice that we do know the type of mySet, namely that it's a TreeSet<int>. That's the key piece of information that tells us which exists() function to call.
Exactly. The type is right there in the program, and so it knows to call
TreeSet<int>'sexists()function. That's pretty obviously the right choice.
Is it…?
I think so! Use the type of the variable (as shown in the program's code) to know what function to call!
We'll see just how good an idea it is.
Hay, I have another question! What if I wanted to write more general code, that didn't mind what kind of set class it had so long as it could call
insert()andexists()on it. Could I do that?
Yes! We can write a template function that doesn't care what kind of “set” it's working on:
template <typename Set>
void doStuff(Set& someSet) {
// ... code ...
std::cout << someSet.exists(42);
}
Our generic doStuff() function doesn't say what Set will be (and so doesn't know which exists() function we want to call), but when we write
TreeSet<int> mySet;
// ... more code ...
doStuff(mySet);
the C++ compiler stamps out an instance of doStuff() where Set is TreeSet<int>, so once again the compiler does know the real type of someSet and thus which exists() function to call.
Cool!
Okay, but we were asked to make a function. Is this really one function? Isn't a function template an infinite family of functions, one for every possible
Settype? If we make both adoStuff<TreeSet<int>>instantiation and adoStuff<HashSet<int>>instantiation, haven't we stamped out two functions?
Well, technically, yes, but we only wrote one…
In Java you can use inheritance and subclasses, does C++ have that too?
It does!
I want to know MORE!
Okay…
(When logged in, completion status appears here.)