Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit operator= call (T::operator=)

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?

like image 609
Victor Polevoy Avatar asked Oct 09 '15 09:10

Victor Polevoy


2 Answers

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"
}
like image 76
SingerOfTheFall Avatar answered Sep 29 '22 00:09

SingerOfTheFall


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.

like image 31
Arne Mertz Avatar answered Sep 28 '22 23:09

Arne Mertz