mardi 25 octobre 2022

Copy internal details from other object with abstract data type

I want a derived class to be able to copy from another class if it has the same type, if not just do nothing.

Example in semi-pseudocode:

class Animal
{
public:
  virtual void CopyFrom(Animal* animal) = 0;

  // TODO: virtual destructor
};

class Dog : Animal
{
public:
  Dog() {}

  void CopyFrom(Animal* animal) override {
    if (animal is Dog) {
      likes_to_bark = ((Dog)animal).likes_to_bark;
    }
  }

private:
  bool likes_to_bark;
}

I know this can be achieved a dynamic cast, but that is considered code smell. I was looking into the visitor pattern and double dispatch, but I could not find a way to do this. Any ideas?

Aucun commentaire:

Enregistrer un commentaire