Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialisation lists in constructors trying to initialize a structure

Tags:

c++

g++ (GCC) 4.6.0

I have the following class and I am trying to initialize in my initialization list of my constructor.

class Floor_plan
{
private:
    unsigned int width;
    unsigned int height;

    struct floor_size {
        unsigned int x;
        unsigned int y;
    } floor;

public:
    Floor_plan() : width(0), height(0), floor.x(0), floor.y(0) {} {}
    Floor_plan(unsigned int _width, unsigned int _height, unsigned int _x, unsigned int _y);
    ~Floor_plan() {};

    unsigned int get_floor_width();
    unsigned int get_floor_height();
    void set_floor_width(unsigned int _width);
    void set_floor_height(unsigned int height);

    void print_floorplan();
};

I have a structure I am trying to set the initial values to. However, I kept getting the following error:

expected ‘(’ before ‘.’ token

I have also tried doing it the following way:

Floor_plan() : width(0), height(0), Floor_plan::floor.x(0), Floor_plan::floor.y(0) {}

However, that results in the following error:

expected class-name before ‘.’ token

Many thanks any suggestions,

like image 788
ant2009 Avatar asked Jun 05 '11 14:06

ant2009


1 Answers

See default init value for struct member of a class

Either you initialize it inside the constructor

Floor_plan() : width(0), height(0), floor() {
  floor.x = 1;
  floor.y = 2;
}

Or you create a constructor for the struct, and use that in the initialization list.

struct floor_size {
    unsigned int x;
    unsigned int y;
    floor_size(unsigned int x_, unsigned int y_) : x(x_), y(y_) {}
} floor;

Floor_plan() : width(0), height(0), floor(1, 2) {}
like image 188
Gilad Naor Avatar answered Sep 21 '22 03:09

Gilad Naor