简体   繁体   中英

calling function whose name is class name itself?

I do not know what methodology they use since the code base is huge .

It defined a class like this:

class ABC {
    member_func(string c);
};

main() {
    ABC("").member_func("this random string");
}

What is the missing code that would enable us to call ABC(""); ?

I did not see any object of that class created anywhere.

That simply constructs an object of type ABC , but doesn't initialize any permanent memory location with that object. Ie, the initialized object the call to the ABC constructor creates is a temporary, and is lost after the call since it is not constructed in a memory location that can be accessed after the call such as an automatic variable on the stack, a static memory location, etc. So the "missing" code to make a call like that usable in the "real-world" is to actual name an object that is constructed so that it can be accessed later... for example, something like ABC my_object(""); or ABC my_object = ABC(""); .

UPDATE: In the updated code you've posted, what's taking place is again a temporary object of type ABC is being constructed, and then a non-static method of class ABC called member_func is being called on the temporary that was created by the call to ABC 's constructor. Of course for this code to have any meaning in the "real world", that call to member_func would have to contain some side-effect that would be visible outside of the class instance (ie, the class instance could be containing a data-member that is a pointer to some shared memory object that the call then modifies). Since though from the code sample you've posted there does not seem to be any side-effects from the call, it's for all intents and purposes a non-operation ... a temporary ABC class instance is created, it has a method called on the instance, and then any reference to the instance is lost since it was not constructed in a memory location accessible from the current scope of main() .

class ABC
{
    std::string d;
public:
    ABC(std::string x)         // For the ABC("").
    { d = x; } 

    void foo(std::string x)    // For the foo("").
    { std::cout << d << std::endl << x << std::endl; }
};

int main()
{
    ABC("This creates a temporary object.").foo("This calls foo().");

    // Is the same as...

    {
        ABC obj("This creates another object.");
        obj.foo("This calls obj.foo().");
    } // obj is destroyed.

    return(0);
}

Self explanatory... I hope. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM