Search code examples
c++multiple-inheritancediamond-problem

Trouble with multiple inheritance. How to call base function?


I'm learning C++ and in a school assignment I must use a diamond structure even if it is not totally correct.

class Book
{
    public:
        virtual int getPurchasePrice() const;
    protected:
        int m_purchasePrice;
};
class AdultBook: virtual public Book{} ;
class ChildrenBook: virtual public Book{} ;
class ComicBook: public AdultBook, public ChildrenBook {} ;

(I removed every methods and constructors to simplify)

Now, if I want to create a ComicBook and to know its purchasePrice, how can I do ? If I do getPurchasePrice() on a ComicBook I get the following error:

error: request for member 'getPurchasePrice' is ambiguous

I thought that putting virtual for ChildrenBook and AdultBook would solve the ambiguity ?


Solution

  • You use either

    obj->AdultBook::getPurchasePrice();
    

    or

    obj->ChildrenBook::getPurchasePrice();
    

    or

    obj->Book::getPurchasePrice();
    

    For obj of type ComicBook

    EDIT FOR Emilio Garavaglia

    Lets assume that you have not redefined getPurchasePrice for adult and childrens book, you could have this

    Key A - Adult book, C - Childrens book, CB - Comic Book, B - Book

    enter image description here