Using initializer lists

I am trying to write a program that will initialize a new "Square" object with private const data member "side". I have written it properly to do so, but I need to write in a check to make sure "const char* token[1]" is not a NULL pointer, and if it is, to initialize"side" to 0 instead. Here's what I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Square // shapeID = 1
{
  const double side;

public:
  Square(const char* const []); // constructor
  void print() const;
};

Square::Square(const char* const token[]) : side(atof(token[1]))
{

}
Last edited on
1
2
3
Square::Square(char const *const token[])
    : side(token[1] == NULL ? 0 : atof(token[1]))
{}


The ternary operator (condition ? return if true : return if false) is shorthand notation for an if-else statement.

But why do you need to pass an array of strings to construct a Square? And why will the side length be stored in the second and not first index?


Random Note:
I am assuming you are programming in C++ since you are using classes, so I suggest you use std::string and std::istringstream instead of working with C-strings manually.
Thanks a bunch! That worked just as I needed it to! The reason its in the second index is because the first index identifies the shape (SQUARE, RECTANGLE, etc) and subsequent tokens are sides, length, radius depending on the shape.

The reason its like that is because the sides and such are parsed from a text file. Also I could use strings, but that's not what the assignment criteria called for.
Last edited on
Well, I would still suggest you leave the converting from C-string to floating point outside of the constructor. It just makes your class more sensible that way. Plus, you can centralize all the conversions somewhere else.
1
2
3
4
5
6
7
Square::Square(double newsidelength) : side(newsidelength) {}

//...

char const * tokens[];
/*Read info from file...*/
Square mysq(token[1] == NULL ? 0 : atof(token[1]));
Topic archived. No new replies allowed.