Question

I am new to Java (working on Android). I have seen code like,

new DownloadFilesTask().execute(url1, url2, url3);

Here nameless (I am not sure if I am using correct terminology) object is used to call execute method of DownloadFilesTask's object.

Same I tried to use with C++ and following is code snippets.

#include <iostream>
#include <vector>

using namespace std;

class Sam
{
public:
    void Access()
    {
        cout<<"Access";
    }
};

int main(int argc, char* argv[])
{
    (new Sam())->Access; //for Access method intillesence is working fine

    return 0;
}

When I try to run this code I get compilation error,

Error 1 error C3867: 'Sam::Access': function call missing argument list; use '&Sam::Access' to create a pointer to member c:\users\new-user\documents\visual studio 2012\projects\autoexample\autoexample\autoexample.cpp 18 1 autoExample

I do not understand meaning and reason of error. Is this type of code possible in C++?

Thanks.

Was it helpful?

Solution

As what's been said on the comments, you are lacking the parentheses needed to call the method.

Access()
//    ^^ These

However, a more important issue to be solved here is your use of new. Don't use it like you're using it now. By using it that way, you are creating a memory leak which you can never ever hope to reclaim because you would never have the chance to use delete on it[1] (unless you close your program...).

To use temporaries in C++, just use a stack-based, automatic storage object (in other words, normal objects):

  Sam().Access();
//^^^^^ This creates the temporary object

However, you must still be careful not to use that temporary in subsequent statements, a problem which is commonly encountered when mixing them with references.

Sam& bad_sam = Sam().I_Return_A_Reference_To_This_Object();
bad_sam.Access();   // Oh no!

In the above example, the temporary object created by Sam() will be destroyed at the end of the statement (hence being temporary). bad_sam.Access(); would be illegal and would result in undefined behavior.


[1] Ahem says the language lawyers. Of course you can use delete this;... To OP: don't!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top