Cocomico
Cocomico

Reputation: 888

Qt/C++ Override function without subclassing

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

overriding methods without subclassing in Java

Not sure if there is a way in c++ too. Any ideas?

Upvotes: 6

Views: 3038

Answers (2)

eerorika
eerorika

Reputation: 238361

You can't override without inheritance. The code in the linked example does subclass. Perhaps the confusion comes from the fact that it doesn't use the extends keyword. It creates an anonymous subclass of XStream and overrides it's method. Such classes exist in C++ as well and similar code is possible. The naming convention is a bit different. Classes that have no name, but do have a named instance are called unnamed . Here is my transliteration of the code to show how the example can be done with 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's creating another nested anonymous class, but i'll keep this simple
            }
        } xstream;
    }
};

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

Anonymous classes are often used for callbacks in Java. But in C++ we have function pointers and lately lambdas, which is probably why the use of unnamed classes is much rarer in C++ code compared to Java. Also, before c++11 unnamed classes were not allowed as template parameters, so they would have been a poor choice for a callback functor.

In c++, an Anonymous class (or struct) would be one that has no named instance either. It could be a member of another, outer class and the members of the anonymous class would be brought to the namespace of the parent class. Except, anonymous classes are not allowed by the standard. How can there be a definition for such thing then? Well, anonymous unions are allowed and anonymous classes are analoguous to them. Anonymous structs are allowed by C11 standard, though.

Upvotes: 11

TonyK
TonyK

Reputation: 17114

Your Java example is a subclass -- it's just an anonymous subclass. The @Override keyword is simply a diagnostic aid: it issues an error if the method doesn't override a superclass. Removing @Override has no effect on the generated code. C++11 has it too -- see this link.

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

Upvotes: 7

Related Questions