mercredi 29 janvier 2020

How to return a valid pointer in a factory method to derived class based on underlying OS

I am unable to call private methods of derived class using pointer to base class returned by Factory method.

I would like to return a unique_ptr to Cat when user is running on WIN and unique_ptr to Dog when user is running on Linux.

Base.h pure virtual class

#include <iostream>
#include <memory>

class Base
{
public:
    virtual void echo() = 0;
};

Cat.h - derived class of Base

#include "Base.h"

class Cat : public Base
{
public:
    void echo();
    void CatPrivateFunction();
};

Cat.cpp

#include "Cat.h"

void Cat::echo()
{
    std::cout << "In echo()" << std::endl;
}

void Cat::CatPrivateFunction()
{
    std::cout << "In CatPrivateFunction()" << std::endl;
}

Dog.h - derived class of Base

#include "Base.h"

class Dog
{
    void echo();
    void DogPrivateFunction();
};

Dog.cpp

#include "Dog.h"

void Dog::echo()
{
    std::cout << "In echo()" << std::endl;
}

void Dog::DogPrivateFunction()
{
    std::cout << "In DogPrivateFunction()" << std::endl;
}

BaseFactory.h

#ifdef _WIN32
#include "Cat.h"
#elif __linux__
#include "Dog.h"
#endif
#include <memory>

class BaseFactory
{
public:
    static std::unique_ptr<Base> createBase();
};

BaseFactory.cpp

#include "BaseFactory.h"

std::unique_ptr<Base> BaseFactory::createBase()
{
#ifdef __linux__
        return std::unique_ptr<Base>(new Dog{});
#elif _WIN32
        return std::unique_ptr<Base>(new Cat{});;
#endif
}

In the following script

#include "BaseFactory.h"
int main()
{
    std::unique_ptr<Base> p = BaseFactory::createBase();
    p->echo();
    p->CatPrivateFunction();
    return 0;
}

I'd expect the following output

In echo()
In CatPrivateFunction()

But p->CatPrivateFunction() is failing as Base.h doesn't have CatPrivateFunction() member function.

How can this be done?

Aucun commentaire:

Enregistrer un commentaire