chriss
chriss

Reputation: 31

Pointer to table of object

I want to use foo array of objects in all of Spam methods.

#include "spam.h"
class Foo: public Bar
{
public:
   Foo(Layer* layer)
   int getNumber() const;
   // Something else
};

class Spam: public Layer
{
  Spam();
  // some methods
private:
  Bar** foo;  //here is the problem
};

This method (of course with one *) worked for me when I was creating one object.

void Spam::fun1()
{
  Bar **foo = new Bar*[1];
  foo[0] = new Foo(this);
  //foo[1] = new Foo(this);

  //foo[1]->getNumber(); // works correctly
}

void Spam::fun2()
{
  //foo[1]->getNumber(); // foo[1] and foo[2] are NULL
  foo[0]->getNumber():   // not working at all

}

But even I use Bar** foo or Bar** foo[2], Xcode shows me that I created new pointer to object.

Xcode screenShoot

[edit]I commented out wrong code example, my oversight, thanks guys.

Upvotes: 0

Views: 708

Answers (3)

Nitheesh George
Nitheesh George

Reputation: 1367

In method Spam::fun1() you allocated memory to a local variable "foo" of type "Bar **". Instead you have to allocated memory for your class member variable "foo". Two things you can do to solve this issue,

  1. Remove the local variable declaration of "foo" for this use the below code instead of "Bar **foo = new Bar*[1];" inside "Spam::fun1()".

    foo = new Bar*[1];

  2. If you wanted to keep the local variable due to some reasons, use "this" pointer to indicate the class member,

    this->foo = new Bar*[1];

Just a suggestion, you can avoid these kind of confusions, if you follow proper naming conventions in your source code like below.

class CSpam: public CLayer
{
private:
Bar ** mFoo;
};

void Spam::fun1()
{
  mFoo = new Bar*[1]; 
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477150

In your fun1, the statement Bar **foo = new Bar*[1]; defines a new, local variable foo, which hides the class member name.

If you want to refer to the class member instead, say foo = new Bar*[1];.

Upvotes: 2

geofftnz
geofftnz

Reputation: 10092

It looks like you have a buffer overflow here:

Bar **foo = new Bar*[1];   // allocate one-element array of pointers to Bar
foo[0] = new Foo(this);    // valid assignment
foo[1] = new Foo(this);    // off the end of the array.

Upvotes: 0

Related Questions