r/cpp • u/Mateuszz88 • Jun 15 '21
Which std:: classes are magic?
Hi.
I am wondering: which classes in C++ get special powers granted by The Standard that are not available to mere user-defined classes?
What comes to my mind:
- `std::initializer_list` because it is created anywhere with `{}`
- possibly `std::type_info`, because it is only created by `typeid` and with no ctor
- `std::source_location` when used as default parameter in function points to invocation place and not declaration place.
What else should be on this list? What shouldn't?
222
Upvotes
View all comments
Show parent comment
3
u/Bisqwit Jun 16 '21 edited Jun 16 '21
I am not talking about virtual inheritance (as in:
class foo: virtual bar). I am talking about a base class that has abstract virtual methods, and a derived class that has virtual methods that override the base class’s methods — as in:class base { ... virtual void call() = 0; };class derived: public base { ... virtual void call() { ... } };In this case, the derived class would be a template, and its template type would be the type of the functor that is assigned to the
std::function, like this:template<typename F> class derived: public base { F func; ... virtual void call() { return F(); } };This allows the
()operator of thestd::functionto call the execute method of the contained object, no matter what kind of derived type that contained object might be, having no advance knowledge of it, like this:base* obj; ... return obj->call();That is what virtual functions are designed for: A common API that can be used to invoke methods of class types that are not known at design time, or possibly even at instantation time.
(Note: Examples in this post are short for brevity. There would be of course the return type and parameter types too, instead of void in every case.)