Reputation: 175
I would like to identify which child classes initialize pointers in a vector.
I prepare a vector that contains different types of override classes. After that, I set it as an argument in the same function. In the function, I would like to identify which classes initialize this argument and apply different processes for each class.
This is the code and current output.
#include <memory>
#include <iostream>
#include <vector>
class Parent
{
public:
Parent() {};
virtual ~Parent() {};
virtual void print()
{
std::cout << "I am parent!" << std::endl;
}
};
class ChildA : public Parent
{
public:
ChildA() {};
~ChildA() {};
void print() override
{
std::cout << "I am child A!" << std::endl;
}
};
class ChildB : public Parent
{
public:
ChildB() {};
~ChildB() {};
void print() override
{
std::cout << "I am child B!" << std::endl;
}
};
void func(std::unique_ptr<Parent>& pa)
{
pa->print();
//if (pa is initialized from Parent)
//{
//}
//if (pa is initialized from ChildA)
//{
//}
//if (pa is initialized from ChildB)
//{
//}
return;
}
int main(int argc, char** argv)
{
std::unique_ptr<Parent> pa = std::make_unique<Parent>();
std::unique_ptr<ChildA> chA = std::make_unique<ChildA>();
std::unique_ptr<ChildB> chB = std::make_unique<ChildB>();
std::vector<std::unique_ptr<Parent>> mList;
mList.push_back(std::move(pa));
mList.push_back(std::move(chA));
mList.push_back(std::move(chB));
for (auto& l : mList)
func(l);
return 0;
}
output
I am parent!
I am child A!
I am child B!
Could you tell me any idea? Thank you.
Upvotes: 0
Views: 54
Reputation: 68561
The purpose of doing polymorphic code with virtual functions is usually so you can avoid doing "is this an X" style tests. Instead you create a virtual function doSpecialStuff
in the base class and call it via a base class pointer (like print
in your code), which then does the appropriate operations for each derived class.
If you really want to test the type, use dynamic_cast
:
if(auto child_ptr=dynamic_cast<ChildA*>(pa.get())){
child_ptr->child_A_function();
}
Upvotes: 1