Re: Silly C++ OOP question
Spaceman Spiff schrieb:
Just playing around with C++ and mostly for pedagogical reasons I
created a this useless code: http://pastebin.com/gfRipZbS.
Compiling this on linux with gcc gives me this compilation error:
$ g++ src/main/cpp/time*.cpp -o target/time
/tmp/ccWgcXcG.o: In function `acme::Time::Time()':
timecheck.cpp:(.text._ZN4acme4TimeC2Ev[acme::Time::Time()]+0xf):
undefined reference to `vtable for acme::Time'
/tmp/ccWgcXcG.o:(.rodata._ZTIN4acme8TimeImplE[typeinfo for
acme::TimeImpl]+0x10): undefined reference to `typeinfo for
acme::Time'
collect2: ld returned 1 exit status
I've tried to look this up and the best I could try was to make sure
all virtual methods were implemented and I also tried defining
something that wasn't inline, which didn't work. So I am left
scratching my head and muttering wtf. Can anyone help me out here?
In time.h, you declare the class time.h, from which you derive TimeImpl.
However, you never define the methods of acme::Time, and thus the
compiler complains. If acme::time is designed for polymorphic usage, and
you attempt to define an abstract interface by a *pure virtual* base
class, then you need to tell the compiler. Specifically, tell the
compiler explicitly that you do not want to provide implementations of
the member functions:
namespace acme {
class Time {
public:
virtual int getHour() const = 0;
virtual int getMinute() const = 0;
virtual int getSecond() const = 0;
virtual void setHour(int) = 0;
virtual void setMinute(int) = 0;
virtual void setSecond(int) = 0;
virtual void setTime(int, int, int) = 0;
virtual const char* toString() const = 0;
};
}
However, unless you really *attempt* to use acme::Time polymorphically,
I simply wouldn't use virtual member functions here because it doesn't
gain anything in this specific case.
Further comments: I wouldn't call time.cpp a ".cpp" file because it is
the class definition, which - due to the straightforward code - already
includes an implementation. Thus, it is actually a header file. In a
longer project, you would split that again into a header, declaring the
concrete class, and a cpp file, defining the implementation. Whenever
you create an instance of the abstract interface acme::time, you need to
create, of course, one of the concrete implementations. (This is then,
probably hidden behind a "factory", but that's another issue.)
HTHH,
Thomas
In the main program, you shouldn't
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]