Qt / C ++ override function without subclass

I would like to override the QWidget virtual function without subclassing it. It is possible in java. I found this link:

overriding methods without subclass in Java

Not sure if there is a way in C ++ either. Any ideas?

+5
source share
2 answers

You cannot override without inheritance. The code in the related example makes a subclass. The confusion is probably due to the fact that it does not use the extends . It creates an anonymous subclass of XStream and overrides it. Such classes exist in C ++, and similar code is possible. The naming convention is slightly different. Classes that do not have a name but have a named instance are called unnamed † . Here is my code transliteration to show how an example can be executed with an unnamed class in C ++:

 class SomeClass { public: void myMethod() { class: public XStream { protected: MapperWrapper wrapMapper(const MapperWrapper& next) override { return MapperWrapper(next); // the example is cut off here, persumably it creating another nested anonymous class, but i'll keep this simple } } xstream; } }; 

You can replace XStream with QWidget and wrapMapper with one of its virtual classes if you want to override it this way.

Anonymous classes are often used for callbacks in Java. But in C ++ we have pointers to functions and lambda lately, which is probably why using unnamed classes is much less common in C ++ code compared to Java. Also, prior to C ++ 11, unnamed classes were not allowed as template parameters, so they would be a poor choice for a callback function.

† In C ++, an anonymous class (or struct) will be the same that does not have a named instance. It can be a member of another outer class, and members of the anonymous class will be migrated to the namespace of the parent class. In addition, anonymous classes are not allowed by the standard. How then can there be a definition for such a thing? Well, anonymous unions are allowed, and anonymous classes are similar to them. However, anonymous structures are allowed by the C11 standard.

+11
source

Your Java example is a subclass - it is just an anonymous subclass. The @Override is just a diagnostic tool: it throws an error if the method does not override the superclass. Removing @Override does not affect the generated code. C ++ 11 is there too - see this link .

In C ++, as in Java, you cannot override a virtual function without declaring a subclass. If you want to use Qt effectively, you will have to get used to it!

+7
source

Source: https://habr.com/ru/post/1201311/


All Articles