alias this

Let’s discuss the use of the alias “this”.

We'll cover the following

Use of alias this

You have seen the individual meanings of the alias and the this keywords in previous chapters. These two keywords have a completely different meaning when used together as alias this.

alias this enables automatic type conversions (also known as implicit type conversions) of user-defined types. As have seen in the operator overloading chapter, another way of providing type conversions for a type is by defining opCast for that type. The difference is that, while an opCast is for explicit type conversions, alias this is for automatic type conversions.

The keywords alias and this are written separately, where the name of a member variable or a member function is specified between them:

alias member_variable_or_member_function this;

alias this enables the specific conversion from the user-defined type to the type of that member. The value of the member becomes the resulting value of the conversion.

The following Fraction example uses alias this with a member function. The TeachingAssistant example below will use it with member variables.

Since the return type of value() below is double, the following alias this enables automatic conversion of Fraction objects to double values:

Get hands-on with 1400+ tech skills courses.