R L W
R L W

Reputation: 135

Identifier undefined when called by reference in function

I am trying to pass a vector of "Piece"s (a class I define) by reference into a function, however during compile time I get an error saying "Piece" is undefined. The files currently looks like:

Header.hpp

#pragma once
#ifndef MY_CLASS_H // Will only be true the once!
#define MY_CLASS_H
#include <vector>
//some stuff    
bool make_move(std::vector<Piece*> & vector_of_pieces);
class Piece {
//member functions declarations
};
#endif

nonPieceFunctions.cpp

#include "Header.hpp"
#include<iostream>
#include <array>
#include <stdio.h>
#include <ctype.h>

using namespace std;

bool make_move(vector<Piece*> &vector_of_pieces) {
    string piece_location, piece_new_location;
    cout << "Which piece would you like to move?" << endl;
    while (is_valid_input(piece_location) == false) { //checks input is of the right format
        cin >> piece_location;
    }
    int file_no = get_file_no(piece_location); //gets file number from user input
    int rank_no = get_rank_no(piece_location); //gets rank number from user input
    cout << "File no is " << file_no << endl;
    cout << "Rank no is " << rank_no << endl;
    return true;
}

This is not the complete version of the function I want to make but it currently doesn't compile as it is. No functions in "make_move" are member functions of any class.

Upvotes: 0

Views: 238

Answers (3)

ofir agranat
ofir agranat

Reputation: 90

Either implement the class Piece before the deceleration of make_move():

#pragma once
#ifndef MY_CLASS_H // Will only be true the once!
#define MY_CLASS_H
#include <vector>
//some stuff 
class Piece {
//member functions declarations
};
bool make_move(std::vector<Piece*> & vector_of_pieces);

#endif

or use forward deceleration on the class:

#pragma once
#ifndef MY_CLASS_H // Will only be true the once!
#define MY_CLASS_H
#include <vector>
//some stuff 
class Piece;   
bool make_move(std::vector<Piece*> & vector_of_pieces);
class Piece {
//member functions declarations
};
#endif

Upvotes: 1

CompuChip
CompuChip

Reputation: 9232

You are using Piece in make_move' s declaration, you need to tell the compiler that it will follow later:

class Piece;
bool make_move(std::vector<Piece*> & vector_of_pieces);

class Piece {
//member functions declarations
};

Upvotes: 0

doctorlove
doctorlove

Reputation: 19232

As it stands

bool make_move(std::vector<Piece*> & vector_of_pieces);

comes before the definition of Piece, hence your problem.

Either move this after the class definition.

Or forward declare as follows:

class Piece;
bool make_move(std::vector<Piece*> & vector_of_pieces);

since you are using a pointer in the vector it should work.

BTW - are you deleting these pointers somewhere?

Upvotes: 3

Related Questions