I'm working through the example programs of Wiley's Teach Yourself C++ (7th Edition) using LLVM clang++ (version 3.1 on FreeBSD) as my compiler. In Ch. 23, "Class Inheritance", the following code is provided:
Date.h - the base class:
...snip..
inline void Date::Display(std::ostream& os)
{ os << "Date: " << *this; }
...snip...
SpecialDate.h - the class derived from Date and overloads the Display() function:
#include "Date.h"
...snip...
void Display(std::ostream& os)
{ os << "SpecialDate: " << *this; }
...snip...
23-1.cpp - instantiates an object of SpecialDate and uses it:
#include <iostream>
#include "SpecialDate.h"
int main()
{
...snip...
// da, mo, & yr are all ints and declared
SpecialDate dt(da, mo, yr);
...snip...
dt.Display();
...snip...
When I compile the code, the only error I get is:
./23-1.cpp:14:14: error: too few arguments to function call, expected 1, have 0
dt.Display();
~~~~~~~~~~ ^
./SpecialDate.h:15:2: note: 'Display' declared here
void Display(std::ostream& os)
^
1 error generated.
I can see that I need to pass by reference a std::ostream type variable to Display(), but I'm stumped on how to proceed. FWIW: both Date.h and SpecialDate.h overload the <<
operator. I've tried:
dt.Display(std::cout); /* all sorts of weird compiler errors */
...
std::ostream os; /* error: calling a protected constructor of class */
dt.Display(os);
...
std::cout << dt.Display(); /* same "too few arguments" error */
What do I need to do to get this code to compile?
EDIT:
Chris, clang++ errors for dt.Display(std::cout);
:
/tmp/23-1-IecGtZ.o: In function `SpecialDate::Display(std::ostream&)':
./23-1.cpp:(.text._ZN11SpecialDate7DisplayERSo[_ZN11SpecialDate7DisplayERSo]+0x34): undefined reference to `operator<<(std::ostream&, SpecialDate&)'
/tmp/23-1-IecGtZ.o: In function `Date::Date(int, int, int)':
./23-1.cpp:(.text._ZN4DateC2Eiii[_ZN4DateC2Eiii]+0x34): undefined reference to `Date::SetDate(int, int, int)'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
Also, #include <iostream>
is in both Date.h and SpecialDate.h.
EDIT 2: After re-reading the errors for dt.Display(std::cout);
, I realized that the compiler was not seeing the source for SpecialDate and Date, just the headers. So I added those to the command line and it finally compiled without errors!
clang++ 23-1.cpp Date.cpp SpecialDate.cpp
Unfortunately, the behavior is not as expected (the date is not being displayed), but my original question has been answered. I'll continue to poke at it. Thanks for your patience with a noob!