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.
Aucun commentaire:
Enregistrer un commentaire