Dima Dz
Dima Dz

Reputation: 538

c++ passing element of vector<Parent*> into object's method requiring chidren

In C++, I have Parent class. Child1, Child2, etc. inherit from it. Classes Child1, Child2, etc. share some methods of the parent and have their own methods.

I declare a vector to be able to add any child of Parent.

vector<Parent*> v = {new Child1(), new Child2(),...};

Depending on a child, I want to define different behaviour for a method of BClass::someMethod(Child1* child), BClass::someMethod(Child2* child)... Something like Visitor pattern. The problem is that I must pass an element of v vector into BClass::someMethod(...) and the compiler says, for example for method BClass::someMethod(Child1* c1) when v[0] is passed:

Argument of type Parent* is incompatible with parameter of type Child1* 

Could you please tell me how to overcome the issue?

Upvotes: 0

Views: 97

Answers (1)

eerorika
eerorika

Reputation: 238301

OOP solution is to add a virtual member function to Parent, implement the different behaviour in overridden member functions of children, and change the argument of BClass::someMethod to a Parent pointer (or reference), and call the virtual function in there - or get rid of BClass::someMethod entirely, and use the virtual function directly in case BClass::someMethod no longer has other functionality.


P.S. Storing dynamic allocations in bare pointers is not a good design. Smart pointers are recommended instead.

Upvotes: 4

Related Questions