Birbal
Birbal

Reputation: 63

How Structures are initialized in C++

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?

Upvotes: 0

Views: 92

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69854

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)
{
}

Upvotes: 1

Related Questions