Reputation: 1
I am new to pointers and I am having trouble in accessing the variables inside a class.
I want to make a sort of database of possible moves in a Chess game, and I think that using pointers is the way to go, since I wouldn't be wasting memory and prevent any unnecessary memory errors.
main.cpp
#include <iostream>
#include "moves.h"
using namespace std;
int main()
{
moves* possibleMoves[100];
&(possibleMoves[0]->piece) = 100;
cout << *&possibleMoves[0]->piece << endl;
return 0;
}
moves.h
#ifndef MOVES_H
#define MOVES_H
class moves
{
public:
moves();
int piece;
int X;
int Y;
int addX;
int addY;
int score;
};
#endif // MOVES_H
Any help would be appreciated. Thank you very much in advance.
Currently it doesn't output anything and I don't know what to do.
Upvotes: 0
Views: 42
Reputation: 114
You are creating an array of pointers with:
moves* possibleMoves[100];
when what you want is an array of moves
.
Then you are trying to assign piece
in possibleMoves[0]
a value of 100
with:
&(possibleMoves[0]->piece) = 100;
but you are actually doing something quite different. As @Henri Menke said best to read up on &
, *
, .
and ->
.
To make your intended code work try:
int main()
{
moves possibleMoves[100];
possibleMoves[0].piece = 100;
cout << possibleMoves[0].piece << endl;
return 0;
}
Here you create an array of moves
objects, then assign the value of piece
in object 0 a value of 100. You retrieve the value and print it to cout
.
Upvotes: 0
Reputation: 17678
I am having trouble in accessing the variables inside a class
It looks like you are making a mess of pointers and references.
There isn't a real need in your code to use array of pointers. Instead using normal array of objects would do.
moves possibleMoves[100];
possibleMoves[0].piece = 100;
cout << possibleMoves[0].piece << endl;
Btw, class moves
incorrectly exposes all data members to public - they should be private. And moves
constructor needs to be implemented or otherwise should be removed to use the default one.
Upvotes: 1