2

I've been trying to solve this problem for hours, but I couldn't find the solution. Code example:

class IColor { // color interface public: virtual void print(); }; class Color : public IColor { // abstract color class }; class RGB : public Color { // color implementation public: void print() { std::cout << "hi"; } }; int main() { IColor* col = new RGB(); col->print(); return 0; } 

However, the result of compilation are linker errors:

/home/snndAJ/ccnvQHgL.o:(.rodata._ZTI5Color[_ZTI5Color]+0x8): undefined reference to `typeinfo for IColor' /home/snndAJ/ccnvQHgL.o:(.rodata._ZTV5Color[_ZTV5Color]+0x8): undefined reference to `IColor::print()' collect2: error: ld returned 1 exit status 

(Not)working online example: https://ideone.com/YikYwe

1 Answer 1

5

Change your base class to have a pure virtual member:

class IColor { public: virtual void print() = 0; }; 

As your code stands, you are declaring IColor::print but never defining it, which leads to the unresolved reference that your linker is complaining about. A pure-virtual function requires no definition, and indeed no definition makes sense in this case, since every leaf class must override this method.

In fact, you will most likely also need a virtual destructor:

virtual ~IColor() {} 
Sign up to request clarification or add additional context in comments.

1 Comment

Minor nitpick: A pure-virtual function may have a definition but is not required to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.