Re: Silly C++ OOP question
On 2 Mrz., 14:19, Spaceman Spiff <sardonicstuffedti...@gmail.com>
wrote:
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
Note that these are no compiler errors but linker errors.
Some design hints (I guess you have a Java background):
1) acme::Time seems to be an "interface" class. So, you will
probably want to make all virtual functions pure. To realize
that, write = 0 at the end of the declaration, e.g.
virtual int getHour() const = 0;
2) Your program causes undefined behaviour, because
you call delete in a polymorphic context without having
a virtual destructor in the base class. So add
virtual ~Time(){}
to class acme::Time.
3) The implementation of the toString() function in acme::TimeImpl
returns a pointer to a local variable, which is quite dangerous
because the pointer contents are invalid. I recommend that
you change the return type to std::string.
4) I strongly recommend that you partition TimeImpl.cpp into
TimeImpl.h and TimeImpl.cpp, where TimeImpl.h contains only
the function declaration. And do *not* add using declarations
in namespace scope of a header!
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?
There is the problem that you compile the same class
member functions twice:
Your compile directive to gcc shows that you also tell
the compiler to compile TimeImpl.cpp, but the complete
class (including all member functions) is compiled a
second time within timecheck.cpp. The solution is
to seperate the timeimpl.cpp into a header file that
is included in timecheck.cpp, and a pure implementation
file.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]