0

I am reading TCPPPL by Stroustrup. An exerxise in the book goes somewhat like this:

struct X{
    int i;
    X(int);
    X operator+(int);
};

struct Y{
    int i;
    Y(X);
    Y operator+(X);
    operator int();
};

extern X operator* (X,Y);
extern int f(X);
X x=1;
Y y=x;
int i=2;
int main()
{
//main body
}

My question (maybe a trivial one) is that what is happening in the line: X x =1;? Is a variable x of type struct X being initialized, i.e. its i is being given the value 1? If so, why are there no curly braces around 1?

Birbal
  • 61
  • 7
  • This can be done because `X(int);` is not declared as `explicit`. – llllllllll Mar 08 '18 at 09:04
  • 1
    Somehow a duplicate to [What does the explicit keyword mean?](https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-mean), different question, but should explain everything. – t.niese Mar 08 '18 at 09:06
  • It initializes an `X` `x` with an `int` `1`. There are [various ways](https://stackoverflow.com/q/24953658/3484570) to do that. – nwp Mar 08 '18 at 09:06
  • I'm somewhat surprised that the book doesn't explain this. – molbdnilo Mar 08 '18 at 09:22
  • @molbdnilo: maybe the book explained it somewhere but I didn't read the text. – Birbal Mar 08 '18 at 09:24
  • @Birbal The text is the most important part. Why did you get a book if you're not going to read it? – molbdnilo Mar 08 '18 at 09:29
  • @molbdnilo I am reading the book but I jumped at this exercise, I'll continue reading the book. – Birbal Mar 08 '18 at 09:31

1 Answers1

1

My question (maybe a trivial one) is that what is happening in the line: X x =1;

X defines a constructor that takes one int: X::X(int i)

The statement:

X x = 1;

Is equivalent to:

X x = X(1);

or

auto x = X(1);

or

auto x = X { 1 };

i.e. construct an X using the (int) constructor.

i.e. its i is being given the value 1?

Yes, that's correct**.

** or at least that's what I assume, not having seen the constructor's definition. I have assumed it looks something like this:

X::X(int arg)
: i(arg)
{
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • 5
    "its i is being given the value 1?" No, it depends on how the constructor is implemented. – songyuanyao Mar 08 '18 at 09:09
  • 3
    The statement `X x = 1` is not equivalent to `X x = X(1)`, otherwise both would work for `explicit X(int)`. In the given code they have the same result, because the constructor is not explicit. – t.niese Mar 08 '18 at 09:10
  • @t.niese *in this case* they are equivalent, because they refer to `X`. – Caleth Mar 08 '18 at 09:25