Question

I have a class 'D' which has a member function 'play'. Play is supposed to take two parameters, both objects of class 'A'. I have two other classes, 'B' and 'C', which are both inherited (protected) from class 'A'. The way my program is structured, I only have an object of 'B' and another of 'C' to pass to function 'play'. How can I make this work? If I pass these two inherited objects, I get a compiler error:

cannot cast 'B' to its protected base class 'A'

Do I need to cast the objects back to 'A' objects to be able to pass them to 'play'? Or can I somehow use them as is?

Était-ce utile?

La solution

You can pass object of class B and class C by reference. ex: void play(A* b,A* c);

since B and C is the child of A, the pointer of A can hold the object. but you need to declare all the functions of B and C which you want to use in Class D inside Class A.

Autres conseils

If I've correctly interpreted your code and your situation is the following:

struct A {};
struct B : protected A {};
struct C : protected A {};
struct D {
    void play(A a, A b) {}
};

then you should inherit publicly and accept const references (or references) in the play member function, like this:

struct A {};
struct B : public A {};
struct C : public A {};
struct D {
    void play(A const& a, A const& b) {}
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top