Reputation: 69
I've created an object that takes a multidimensional array (a grid) as an argument (char grid[][20]
), as well as a vector of those objects (to which it will belong).
The constructor assigns the member variable char (*my_grid)[20]
to the argument, so that the object functions can change the original grid. This already works - I can assign my_grid[x][y]
to different values, and it changes the original 'grid'.
I want to create a member function that creates another new object (from within the original object), passing 'my_grid' as the argument (the new object will be added to the original vector of objects).
However, the compiler says that my_grid
is a char(*Object::my_grid)[20]
when what I need is a
char(*)[20]
. I don't understand the difference. How do I pass the grid as an argument in the object member function, to create a new object? Thanks.
Object has member variable: char(*my_grid)[20];
Constructor:
Object::Object(char the_grid[][20], vector<Object>& the_objects)
{
my_grid = the_grid;
my_objects = &the_objects;
}
Object Member Function:
void Object::new_object()
{
Object second_object(my_grid, my_objects); //this doesn't work
}
Upvotes: 0
Views: 82
Reputation: 320461
The obvious error in your code is actually related to the second constructor argument. Inside Object::new_object()
you attempt to pass my_objects
to the constructor, which implies that my_objects
has type vector<Object>&
or vector<Object>
. However, inside the constructor you initialize my_objects
with &the_objects
, which implies that my_objects
has type vector<Object> *
. This is self-contradictory.
So, what is the declared type of my_objects
?
However, in any case this is a problem with the second argument of your constructor. The error message you quoted refers to the first argument and my_grid
member. The error message makes no sense in the context of the code you posted so far. There's no such error there. Either your compiler is broken, you are posting fake code or you are misquoting the error message.
In any case, try fixing the problem with the second argument and see it it helps.
Upvotes: 1
Reputation: 2074
char (*something)[20]
would be just a regular pointer to a character array.
char (*Object::something)[20]
is a pointer-to-member type.
This is a type that says "If we have an Object
, then it will have a member variable of type char[20]
at this location." Its usage is like so:
class Object
{
public:
int a;
char b[20];
};
/* ... */
//Acquire the location of 'b' relative to any 'Object'
char (*Object::myPtrToMemberB)[20] = &Object::b;
int (*Object::myPtrToMemberA) = &Object::a;
Object x;
//Access member 'b' via ptr to member
x.*myPtrToMemberB[0] = 'b';
//Access member 'a' via ptr to member
x.*myPtrToMemberA = 127;
Upvotes: 0