onsdag 2 december 2015

A suggestion for a C++1z feature

This is probably quite a controversial proposal. And I am by no standards a very skilled programmer. But anyway, I think this feature could be rather nice to have.

The idea is to have some kind of Post-constructor automatically generated and executed member function. A suggested name for this function would be initializer. It is not entirely clear to me how it should be run, but maybe in reverse compared to constructors, so that derived classes initializers are run before base classes.

The rationale for this proposal is; How many times have you seen code like:

class A{...};
class B : private A{...};
B m(param p);
m.Init();

Or something like that. The reason for this construction (that is, why the code that goes into init does not go into the constructor) is that Init calls some interface function from a member of the base class A to the derived class B. Now this interface function for sure will need stuff created when B was constructed, and hence it can not go into A's constructor. It can also not go into B's constructor since, B does not know about all stuff in A.

For this, a really nice solution would be if all classes run Init-functions in reverse automatically. Then if this function is not user created, it does not have to be run. However, if the user created it, it should be run automatically at the end of the constructor. Maybe it could be done in a fashion similar to the init list in the constructor, but appearing at the end of the function declaration instead? Something like:
B::B(param p) : ...{
...
} : !A()
Where I named the function !A.

Inga kommentarer: