C++ creating an object and using it in the same line

Viewed 4792

I'm fairly new to C++ and was wondering about this:

Suppose I need to create an object x of the class X and call its function foo() which returns an object y of type Y. I don't need x anymore after I have obtained y.

Currently, I do something like this: (suppose a and b are parameters to X's constructor)

X x(a,b);
Y y = x.foo();

However, for readability issues, I would like to do these things in a single line. Also, it's pointless to have the name x lying around.

My native programming language is Java, where I would do something like this:

Y y = (new X(a,b)).foo();

I apologize for asking such a basic question, but my searches delivered nothing, since most of them returned results about the C++ inline keyword, which is completely unrelated to the matter.

3 Answers

Building upon the code samples here, I was curious and went to play a bit.

#include <iostream>

struct Person
{
    int age = 5;

    Person()
    {
    };

    Person(int newage) : age(newage)
    {
    };

    Person getNewPerson()
    {
        return Person();
    }

    void printAge()
    {
        std::cout << age << std::endl;
    }
};

int main(int argc, char *argv[])
{
    Person person;
    person.getNewPerson().printAge();       // 5

    Person p2 = Person(6).getNewPerson();
    p2.printAge();                          // 5

    Person p3 = Person(6);
    p3.printAge();                          // 6

    Person(9).getNewPerson().printAge();    // 5

    Person(9).printAge();                   // 9

    return 0;
}
Related