Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class name as class member

Tags:

c++

What's the meaning of the postfix expression AttrNode().AttrNode in main in the following code? Both gcc and clang can compile the code without any error. Seems it is legal in C++ standards. But what's the meaning of such code? Why does the C++ standards allow such usage?

#include <stdio.h>

struct AttrNode {
public:
     AttrNode() {}
     static void make() {}
};

int main() {
    AttrNode().AttrNode::make();
    return 0;
}

Thanks!

like image 220
writalnaie Avatar asked Feb 11 '23 01:02

writalnaie


1 Answers

AttrNode:: is qualifying the name make, to explicitly call AttrNode::make and not any other function called make.

In this case, that's redundant; AttrNode().make() would do exactly the same thing: create a temporary object, call the function, then destroy the object. Since it's a static function, you would usually call it without making an object, AttrNode::make().

It makes a difference if it's a virtual function, causing a non-virtual call to the function in the specified class, rather than a virtual call the final override. The syntax can also be used to access a name in the base class that's been hidden in a derived class.

like image 86
Mike Seymour Avatar answered Feb 15 '23 10:02

Mike Seymour