logoalt Hacker News

loegyesterday at 10:16 PM2 repliesview on HN

The aside about C++ seems a little confused too?

> C++ doesn’t have this problem at all, since virtual dispatch always goes through pointers and return types are always pointers too.

Uh. C++ can return objects by value. Maybe it isn't idiomatic. And I don't know if there's a convenient spelling like `Self`. But it runs into the same problem, of course -- you would need to know the concrete value type returned to have storage for it.

And Rust has the ~same solution as imagined for C++ here, I think? Have a `DynClone` trait that returns `Box<dyn Trait>` instead of `Self`.


Replies

neerajsiyesterday at 10:29 PM

I agree with what you're saying. It's called: https://en.wikipedia.org/wiki/Object_slicing. Clearly a footgun in c++. You have to return a pointer to something that is not locally allocated.

gmueckltoday at 12:54 AM

Polymorphism in C++ can only be correct on pointers and references (which are pointers internally).

Stack-allocated objects and polymorphism only combine if the object is initialized as its true type and a pointer or reference to it is handed out. Obviously, this can create object lifetime issues if the pointer or reference escapes the lifetime of the stack frame containing the object.

show 1 reply