jeudi 9 janvier 2020

What is the issue with this factory function?

In the below code, I write a factory method to create objects of a type in a class heirachy.


#include <iostream>
#include <memory>
using namespace std;

enum Type {
    _Base, _A, _B, _C
};

class Base{
private:
    Type type = _Base;
public:
    virtual Type getType(){
        return type;
    }};

class A : public Base{
private:
    Type type = _A;
public:
    using Base::Base;
};

class B : public Base{
private:
    Type type = _B;
public:
    using Base::Base;
};

class C : public Base{
private:
    Type type = _C;
public:
    using Base::Base;
};

shared_ptr<Base> letterFactory(Type which){
    shared_ptr<Base> base = make_unique<Base>(Base());
    switch (which){
        case _A:
            base = make_unique<Base>(A());
        case _B:
            base = make_unique<Base>(A());
        case _C:
            base = make_unique<Base>(C());
    }
    return base;
}


int main(){
    shared_ptr<Base> instanceOfA = letterFactory(_A);
    cout << instanceOfA->getType() << endl;

    shared_ptr<Base> instanceOfB = letterFactory(_B);
    cout << instanceOfB->getType() << endl;

    shared_ptr<Base> instanceOfC = letterFactory(_C);
    cout << instanceOfC->getType() << endl;

    return 0;
};

The output is

0
0
0

How can I make the output

1
2
3

Aucun commentaire:

Enregistrer un commentaire