Explicit operator= call (T::operator=)
Asked Answered
G

2

5

I am reading qt sources and I've seen a code like this many times:

buttonOpt.QStyleOption::operator=(*opt);

So, I guess it is something like buttonOpt = *opt but why do they use this syntax instead of default and user-friendly? Is this faster or any other profit exists?

Generation answered 9/10, 2015 at 9:12 Comment(0)
V
8

This is because they are explicitly calling the operator= from the base class of buttonOpt, which is QStyleOption.

buttonOpt.QStyleOption::operator=(*opt);

//similar behavior
class Base
{
public:
    virtual bool operator<(Base & other)
    {
        std::cout << "Base";
    }
};

class Derived : public Base
{
public:
    bool operator<(Base & other) override
    {
        std::cout << "Derived";
    }
};

int main()
{
    Derived a;
    Derived b;
    a < b; //prints "Derived"
    a.Base::operator <(b); //prints "Base"
}
Video answered 9/10, 2015 at 9:16 Comment(0)
C
5

The code you show is explicitly calling the base class assignment, i.e. only the base class parts of the QStyleOptionButton get assigned, but not the member variables of the object.

It appears from the documentation, that no operator= is declared for QStyleOptionButton, so if one would call the usual assignment on such an object, the compiler would try to generate such an operator, consisting of the assignment of each base class subobject and each member variable.

Such a generated operator may or may not compile, depending of whether all members and base classes are copyable. In such cases it is usual to define the operator manually, to do the assignment correctly, if the class should be copyable at all.

However, the probable reason to call the base class assignment explicitly is that indeed only the base class parts need to be copied, while the other class members should not be changed, so this is not a "real assignment" in the semantical sense.

Cannula answered 9/10, 2015 at 9:42 Comment(1)
This is a great answer, although the accepted answer is correct, this answer explains the why.Materiel

© 2022 - 2024 — McMap. All rights reserved.