mercredi 24 février 2016

Derived operator = with const variables in base class

I'm trying to avoid using the fancy C++11 code to determine the type of an object by using the old fashioned way: enums! Honestly, I find it pretty simple and it fits all my needs.

    enum class Type
    {
        A, B, C, ...
    }

    struct Base
    {
    public:
        Base(Type t) : type(t) { ... }
        virtual ~Base() { ... }

    public:
        const Type type; // SHALL be const!
    }

    struct Derived : Base
    {
    public:
        Derived() : Base(Type::A) { ... }
        ...
    }

    int main()
    {
        Derived d1;
        Derived d2;

        d1 = d2; // Error!

        return 0;
    }

The code above fails at the = operator and sincerely, I dont really know why (please enlighten me). I, however, know that this could be solved by making "type" non-const and private, and have a public getter to it, but since its a struct, I dont want to create any functions in it at all (my choice). Are there any other solutions for this, like making a generic = operator overload or something?

Thanks!

Aucun commentaire:

Enregistrer un commentaire