And it is still possible to keep the Animal overload beside the new Dog and Cat ones. Fulfilling the requirements not to change its code.

 


 

-----Ursprüngliche Nachricht-----
Von: Jonathan Wakely via Std-Proposals <std-proposals@lists.isocpp.org>
Gesendet: Mo 13.04.2026 14:13
Betreff: Re: [std-proposals] Language support for type erasure
An: C++ Proposals <std-proposals@lists.isocpp.org>;
CC: Jonathan Wakely <cxx@kayari.org>;


On Fri, 10 Apr 2026, 10:39 Frederick Virchanza Gotham via Std-Proposals, <std-proposals@lists.isocpp.org> wrote:
In a job interview recently I was given the following code:

    #include <iostream>
    #include <memory>
    #include <string>

    struct Animal {
      virtual ~Animal() = default;
      virtual std::string name() const = 0;
    };

    struct Cat : Animal {
      std::string name(void) const override
      {
        return "Cat";
      }
    };

    struct Dog : Animal {
      std::string name(void) const override
      {
        return "Dog";
      }
    };

    /* DO NOT CHANGE THE CODE BELOW! */

    void print_name(Animal const &a)
    {
      std::cout << a.name() << std::endl;
    }

    int main(void)
    {
      Cat cat;
      Dog dog;
      print_name(cat);
      print_name(dog);
    }

I was told to remove the inheritance, but I wasn't allowed to edit
code beneath the indicated line. 
 
Or you could just add overloads of print_name taking Cat and Dog which works today and is simple to understand. That's the answer I would hope for if I asked that question. 
 
No std::function, no allocations, no hanging reference captures, no new language features needed. Just clear code.
 
-- 
 Std-Proposals mailing list
 Std-Proposals@lists.isocpp.org
 https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals