I can’t remember what it is called, but I know i can do it in Java.
Suppose I have the following:
class Foo
{
public:
Foo() {};
void bar() {};
};
I want to do this:
int main() {
(new Foo).bar();
}
But it doesn’t seem to work. Is there a similar way to do this without having to do:
int main() {
Foo foobar;
foobar.bar();
}
newdynamically-allocates memory and returns a pointer. Class members are obtained using the indirection operator->. I don’t think this is what you’re looking for as you run the risk of causing a memory leak. Simply calling the constructor ofFooallows us to do what we want:By calling the constructor of
Foo, we create a temporary object off of which we can obtain its data members. This is preferred over pointers as we don’t have to deal with memory leaks and deletion of the pointer.