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.
C++ uses stack-allocation by default. That means you don't have to use new, because variables are not pointers. To solve your problem, only remove the new
.
Y y = X( a, b ).foo();
X( a , b )
is a call to a constructor of X
, and .foo()
calls the member function foo
of the rvalue returned by the ctor.
Note that C++ variables lifetime is linked to variable's scope. That means a variable is initializated at the point of its declaration, and destroyed when the program goes out of its scope.
That means (Regardling in your code) the scope of the rvalue created by the constructor call X(a , b )
is that sentence (Y y = X( a, b ).foo();
) only, so the value is destroyed after the end of that sentence. Thats why in general calling ctors in that way is a bad practice.
This compiles for example:
#include <iostream>
struct Person {
Person getRelatedPerson () {
return Person();
}
void printAge () {
std::cout << 5 << std::endl;
}
};
int main (int argc, char *argv[]) {
Person person;
person.getRelatedPerson().printAge();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With