Search code examples
c++objectinheritanceprotected

C++ Pass inherited class to function expecting base class


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?


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.