0

I am reading TCPPPL by Bjarne Stroustrup and I came across the following piece of code (shown below). I have two questions:

  1. Where is the body of the function operator+? I mean there is only the declaration of the function in class X.

  2. What does the line X(int) mean? Is this the constructor with int as a parameter or something else?


 class X { public: void operator+(int); X(int); }; void operator+(X,X); void operator+(X,double); void f(X a) { a+1; // a.operator+(1) 1+a; // ::operator+(X(1),a) a+1.0; // ::operator+(a,1.0) } 
3
  • 1
    The code you've shown does not have the "body" of either the operator+() or the constructor of X, or the two versions of operator+() declared after X. The X(int) declares a constructor of X that accepts an int as argument. Unless the functions are defined (implemented) somewhere else, that code will compile, but linking will fail. Commented Jan 8, 2019 at 12:55
  • @Peter Please, do not write answers into the comments. Commented Jan 8, 2019 at 13:00
  • note that it is rather common for examples to omit the implementation. As the example seems to be mainly about overload resolution, the implementation is not really relevant. Also as Peter already mentioned, the code compiles without, only when you try to link it would fail Commented Jan 8, 2019 at 13:26

2 Answers 2

1

1) Where is the body of the function operator+? I mean there is only the declaration of the function in class X.

The definition (body) of operator+ can be anywhere. The code is obviously not a complete program (there is no main). Therefore, the definitions might be below the shown code or even in another compilation unit.

2) What does the line X(int) mean? Is this the constructor with int as a parameter or something else?

This is a declaration of a converting constructor of class X that accepts an integer as an argument.

Sign up to request clarification or add additional context in comments.

Comments

1

What does the line X(int) mean?

X(int) is a declaration of a constructor accepting a single integer parameter. Definition is missing.

Where is the body of the function operator+

Wherever you defined it.

This code won't work without the correct definitions.

2 Comments

"This code won't work without the definition." That depends on what you mean by won't work. You can compile such a code just fine (e.g., with g++ -c). You just cannot run it or link it.
You're right, I added my comment because of OP, who seemingly isn't so skilled to understand these differences between compilation and linking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.