validate values in a constructor

Hello all I have a question. What is the best way to insure that the x and y values in this class are always less than 20.I am mainly concerned with the constructor and copy constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  Location::Location( )
{  }

Location::Location(   int x, 
		      int y):
		      _x(x), 
		      _y(y) 
{  }

Location::Location(const Location& other) 
{  
	this->_x = other._x;
	this->_y = other._y;
}

Location& Location::operator=(const Location& other)
{
	this->_x = other._x;
	this->_y = other._y;
	return *this;
}

int Location::getXPoint( ) const
{
	return _x;
}

int Location::getYPoint( ) const
{
	return _y;
}

void Location::setXPoint(const int x) 
{
	if (x < 20)
          _x = x;
	
	else
	 _x =_x;
}
	
void Location::setYPoint(const int y)
{
	if (y < 20)
	  _y = y;
	
	else
	 _y = _y;
}
For example you can do the following way

1
2
3
4
Location::Location(   int x,  int y) :
		      _x( x < 20 ? x : 0 ), 
		      _y( y < 20 ? y : 0 ) 
{  }


Or you can throw an exception.
Last edited on
I would make a validation function. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Location
{
public:
    Location(int x, int y)
    : _x(validatePoint(x))
    , _y(validatePoint(y))
    {
    }
    Location(Location const &copy)
    : _x(copy.getXPoint()) //no need to validate in copy ctor.
    , _y(copy.getYPoint()) //can assume that points are already valid from other objects ctor/assignment functions
    {
    }

    void setXPoint(const int x)
    {
        _x = validatePoint(x);
    }
    
    //... Other functions and stuff here
private:
    static int validatePoint(const int x) //works with both x and y points if they have the same constraints.
    {
        return x < 20 ? x : 20; //if x is greater than 20 return 20, or whatever value you want to default it at. 
        //or throw an exception here, or something.
    }
};

Last edited on
Thanks alot guys. I need to mention my intentions these points are on a 20 x 20 array which is a game board I need to make sure these points stay on the board.But I also need to add the players to the board in random locations. My Problem is if i default to 0 , 0 all the incorrect values will place players in the same cell on the board. I am sorry i was not clear. I guess my best option would be to throw an exception or maybe just not add that player to the board? Thanks to all of you who took the time to read this mess of a post.
Last edited on
Topic archived. No new replies allowed.