0

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?

sion
  • 1,367
  • 6
  • 17
  • 21
  • Why did you make the inheritance relationship `protected`? Do you know the difference of `private`, `protected` and `public` inheritance? I believe, that if you did, then you wouldn't ask that question, so I advise to have a look at this post: http://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance-in-c – Alexander Tobias Bockstaller Mar 21 '14 at 12:02

2 Answers2

2

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.

rajenpandit
  • 1,265
  • 1
  • 15
  • 21
1

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) {}
};
Shoe
  • 74,840
  • 36
  • 166
  • 272