stil
stil

Reputation: 5556

Virtual functions and double inheritance

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

Upvotes: 2

Views: 87

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476940

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() {}

Upvotes: 5

Related Questions