In-Class Exercise
Ad-Hoc Polymorphism
This exercise identifies the admissible operations
on an instance of a class and the categories of ad-hoc
polymorphism invoked by a client program.
Given Information
Client Module
Consider the following client program:
// Ad-Hoc Polymorphism
// h15.cpp
#include <iostream>
#include "String.h"
int main() {
String s("Hello Hello"), t;
std::cout << s << std::endl;
t = s;
std::cout << t << std::endl;
s /= 2;
std::cout << s << std::endl;
s /= 2.5;
std::cout << s << std::endl;
t = "Good Bye";
std::cout << t << std::endl;
}
|
String Module
String.h
The header file for the String module
contains the class definition:
// Ad-Hoc Polymorphism
// String.h
#include <iostream>
class String {
char text[61];
int len;
public:
String();
String(const char*);
String& operator/=(int);
void display(std::ostream&) const;
};
std::ostream& operator<<(std::ostream&, const String&);
|
String.cpp
The implementation file for the String module
contains the function definitions:
// Ad-Hoc Polymorphism
// String.cpp
#include <iomanip>
#include <cstring>
#include "String.h"
String::String() {
text[0] = '\0';
len = 0;
}
String::String(const char* c) {
std::strncpy(text, c, 60);
text[60] = '\0';
len = std::strlen(text);
}
String& String::operator/=(int k) {
len = len / k;
text[len] = '\0';
return *this;
}
void String::display(std::ostream& os) const {
os << text;
}
std::ostream& operator<<(std::ostream& os, const String& s) {
s.display(os);
return os;
}
|
Your Task
Instances of Ad-Hoc Polymorphism
Identify
- the admissible operations on a String
type
- the instances of coercion invoked by the client program
- the instances of overloading invoked by the client program
Walkthrough Result
What is the output generated by the client program?
|