0

So I'm working on one problem where it's my job to add some features to a C++ implementation of battleships. All's fine and dandy but I encountered something like this in a constructor for a ship of size two:

class PatrolBoat : public Ship {
    private:
        int x, y;
        char deck[2];
    public:
        PatrolBoat(int x, int y) : x(x), y(y) {
            deck[0] = '_';
            deck[1] = '_';
        }
        virtual void draw(int x, int y){
            cout << deck[y - this->y];
        }
        virtual void shoot(int x, int y){
            deck[y - this->y] = 'T';
        }
};

I understand the first colon - it just inherits from its parent, the Ship class. But what about the part with the constructor: PatrolBoat(int x, int y) : x(x), y(y) {? What does the x(x) and y(y) mean? I can't make sense out of it and couldn't google my way out of the impasse. Could you please help?

Straightfw
  • 2,143
  • 5
  • 26
  • 39

2 Answers2

2

It's the [constructor initialization list].

The main difference between doing it that way and just setting the values in the constructor is that the initialization list allows you to call the contructor that you want directly so if you want to call a non-default constructor you can do that.

Here's an example where you have a Shape class that constructs a Point in its initialization list by calling the Point(x, y) constructor directly rather than requiring a Point() constructor and then setting point.x and point.y separately in the Shape constructor:

class Point {
public:
  Point(int x_, int y_) : x(x_), y(y_) {};
private:
  int x;
  int y;
};

class Shape {
public:
  Shape(int x_, int_y) : point(x_, y_) {}
private:
  Point point;
};

Furthermore, members must be constructed via initialization lists if they do not have a default constructor or are marked as const.

Jason Sundram
  • 12,225
  • 19
  • 71
  • 86
naumcho
  • 18,671
  • 14
  • 48
  • 59
1

It does call the constructors of x and y. It works with user defined constructors as well.

blue
  • 2,683
  • 19
  • 29