I have a Base class, and a Derived class of Base
struct Base{};
struct Derived: public Base{};
I want to make a function that accepts Base*, but has different functionality when passed a Derived*.
void myFunc(Base* base){
std::cout << "myFunc(base)" << std::endl;
}
void myFunc(Derived* derived){
std::cout << "myFunc(derived)" << std::endl;
}
My problem is when I try to use polymorphism, the function doesn't behave as desired because I'm always passing Base*'s.
Base* base = new Base();
Base* derived = new Derived();
myFunc(base);
myFunc(derived);
Outputs:
myFunc(base)
myFunc(base)
Desired outputs:
myFunc(base)
myFunc(derived)
The reason I can't use casting like - (Derived*)derived - is because I'm using an array of Base*
#include <iostream>
struct Base{};
struct Derived: public Base{};
void myFunc(Base* base){
std::cout << "myFunc(base)" << std::endl;
}
void myFunc(Derived* derived){
std::cout << "myFunc(derived)" << std::endl;
}
void myFunc(Base** bases, size_t count){
for(auto i = 0; i < count; i++){
myFunc(bases[i]);
}
}
int main(){
Base* bases[2];
bases[0] = new Base();
bases[1] = new Derived();
myFunc(bases, 2);
}
The reason I can't make myFunc a virtual member function of base, is because I want to encapsulate myFunc's functionality in a separate class to avoid a monolithic base class.
#include <iostream>
struct Base{};
struct Derived: public Base{};
struct DoesStuff{
void doStuff(Base* base){
std::cout << "doStuff(base)" << std::endl;
}
void doStuff(Derived* derived){
std::cout << "doStuff(derived)" << std::endl;
}
void doStuff(Base** bases, size_t count){
for(auto i = 0; i < count; i++){
doStuff(bases[i]);
}
}
};
struct DoesOtherStuff{
void doOtherStuff(Base* base){
std::cout << "doOtherStuff(base)" << std::endl;
}
void doOtherStuff(Derived* derived){
std::cout << "doOtherStuff(derived)" << std::endl;
}
void doOtherStuff(Base** bases, size_t count){
for(auto i = 0; i < count; i++){
doOtherStuff(bases[i]);
}
}
};
int main(){
Base* bases[2];
bases[0] = new Base();
bases[1] = new Derived();
DoesStuff stuffDoer;
DoesOtherStuff otherStuffDoer;
stuffDoer.doStuff(bases, 2);
otherStuffDoer.doOtherStuff(bases, 2);
}
How do I get myFunc to know a Base* is secretly a Derived*. I think I could use typeid, but I'm not sure that's the most appropriate solution. Correct me if I'm wrong.
Base*andDerived*pointer types.virtualactually?dynamic_cast?dynamic_cast, any day