jeudi 23 juillet 2020

How to compare using base class in derived class data

I have base class and derived class in C++.
I want to determine if the data of the derived class is the same using the pointers of the base class.

enum type

enum class FruitType: int{
    Apple,
    Orange,
};

base class

class Base{
public:
    Base(FruitType t): fruit_type(t){}
    FruitType fruit_type;
};

derived class

class Apple : public Base{
public:
    Apple(int i): Base(FruitType::Apple), foo(i){}
    int foo;
};
class Orange : public Base{
public:
    Orange(float f): Base(FruitType::Orange), bar(f){}
    float bar;
}; 

initialize

// initialize
std::vector<Base*> fruit_list_ = { 
                new Apple(42),
                new Orange(0.f),
                new Apple(1) };

Is there any way to check with HasSameData()?

Base* HasSameData(const Base* pCompare){
    for (const auto& list : fruit_list_) 
    {
        if( pCompare->fruit_type == list->fruit_type ){
            // how to check same data...?
            if( /* ... */ ){
                return list;
            }
        }
    }
    return nullptr;
}

int main(){
    // check same data
    Base* pCompare = fruit_list_[2];
    if(HasSameData(pCompare)){
        // I want to return fruit_list_[2] pointer...
    }
}

Aucun commentaire:

Enregistrer un commentaire