Why is it not a compiler error to use the assignment operator on a dereferenced interface pointer?

Why is it not a compiler error to use the assignment operator on a dereferenced pointer to a purely abstract interface? When might this ever be useful? It looks like this can only lead to subtle bugs as I have outlined below.

To have a globally accessible object that implements an interface, with a default that I can override later, I need to use a handle (pointer to pointer or pointer to std :: unique_ptr), or is there another approach?

#include <iostream>

class Interface {
 public:
  virtual int Value() = 0;
};

class Implementation : public Interface {
 public:
  Implementation(int value) : value(value) {}
  int Value() override {
    return value;
  }
  int value;
};

// Set default value
Interface* object = new Implementation(1);
Implementation* object2 = new Implementation(2);

int main() {
    // Why is this line not a compiler error?
    *object = Implementation(3); // Try to override default value
    *object2 = Implementation(4); // Override default value
    // This outputs "14", not "34", why?
    std::cout << object->Value() << object2->Value();
    return 0;
}

      

To work around these issues, and also allow overriding the default in unit tests, I went with the following approach.

// Set default value
static std::unique_ptr<Interface> object(new Implementation(1));
void SetObject(std::unique_ptr<Interface> obj) {
    object.reset(obj.release());
}

int main() {
    SetObject(std::make_unique<Implementation>(2)); // Override default value
    std::cout << object->Value();
    return 0;
}

      

+3


source to share


1 answer


C ++ objects get a operator=

compiler generated method by default . This operator simply applies operator=

to each of the member variables and is not virtual. This means that it will work with members of the static type of the declared pointer. Since Interface

it has no members, members will not be copied. Implementation

has a member, so the member will be copied.



+5


source







All Articles