Pregunta

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 ?

¿Fue útil?

Solución

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

Otros consejos

This is most likely due to the fact that getPurchasePrice is implemented in both AdultBook and ChildrenBook, but not in ComicBook, that inherits two different implementations for a same virtual function.

You have to override getPurchasePrice for ComicBook as well, and eventually implement with a call to one of the two bases's.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top