David Pfau
David Pfau

Reputation: 813

C++: how do I create an object in stack memory that points to the object I am generating it from?

I have a class Foo with a constructor Foo(Bar * b). I want a function inside of the class Bar that returns a Foo that points to that Bar. I try:

Foo& Bar::make_foo() {
  Foo f((Bar*)this);
  return f;
}

but then G++ tells me:

error: variable ‘Foo f’ has initializer but incomplete type

now I know this would work fine in heap memory:

Foo* Bar::make_foo() {
  Foo * f = new Foo((Bar*)this);
  return f;
}

Edit: apparently the problem was due to an incomplete class defintion. However I am still curious if there is an appropriate idiom for returning an object in stack memory.

Upvotes: 1

Views: 106

Answers (2)

Arun
Arun

Reputation: 20383

The following works for me (http://codepad.org/feWQYjtt). Note: I have slightly changed the signature of make-foo, returning reference of local object does not make sense.

struct Bar;
struct Foo {
    Foo( Bar * ) {}
};

struct Bar {
    Foo make_foo() {     // Signature changed
        return Foo( this );
    }
};

int main() {
    Bar barObj;
    Foo fooObj = barObj.make_foo();
    (void) fooObj;
}

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129364

This code is wrong ANYWAY, since it's returning an object on the stack, which means that once you have returned from the function, that space is available for other objects to be stored in - that's not going to end at all well.

Foo& Bar::make_foo() {
  Foo f((Bar*)this);
  return f;
}

As long as Bar is declared as it should be, you should be able to do this fine - aside from the concern with "you are using stack-space that is going to be freed".

Upvotes: 1

Related Questions