Hey everyone,

I'm having an issue with the simplest vector functions. I'm trying to add a Piece object to a vector, but it's data members are being changed when I do... am I missing something?

/* Piece.h */
#ifndef _PIECE_H
#define	_PIECE_H

class Piece {
public:
    Piece();
    Piece(int r, int c);
    Piece(const Piece& orig);
    virtual ~Piece();
    int r;
    int c;
private:

};

#endif	/* _PIECE_H */



#include <stdlib.h>
#include <vector>
#include <iostream>
#include "Piece.h"

using namespace std;

int main(int argc, char** argv) {
    Piece a(1,2);
    
    vector<Piece> vect;
    vect.push_back(a);
    cout << "Inside vector: " << vect[0].c << endl; //prints out 0 instead of 2
    cout << "Outside vector: " << a.c << endl; //prints out 2 like it should

    return (EXIT_SUCCESS);
}

/* Piece.cpp */
//#include "Piece.h"

Piece::Piece() {
   
}

Piece::Piece(int r, int c){
    this->r = r;
    this->c = c;
}
Piece::Piece(const Piece& orig) {
}

Piece::~Piece() {
}

Think about the order of your code. Think about what your program knows before it tries to use something.

If your program begins and it hasn't been told there is a class called "Piece", then how can it add that class to a vector?

Think about the order of your code. Think about what your program knows before it tries to use something.

If your program begins and it hasn't been told there is a class called "Piece", then how can it add that class to a vector?

Sorry, I should be more clear, I'll rearrange it. I'm using Netbeans, so the 3 files I posted are all separate files and are being compiled by Netbeans.

The first thing that jumped out at me was the 'this->'. Why are you doing that? If you're instantiating a class and editing its member variables they should be intrinsic to that instance of the class anyways, so there's no reason to use 'this'.

It's your copy constructor.... remove it and it will work.

Thank you! I don't know why I didn't realize it! lol Now on to the rest of my assignment... We're supposed to use the min-max algorithm to game a Gumoku (connect 5) game. I think if I keep the coordinates (indexes of a multi-dimensional array) of each players pieces in a vector I could be a little more efficient checking over the board

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.