Unbreakable
Unbreakable

Reputation: 8112

Compilation and execution when code is not dislosed; use of ellipsis in code

In an interview I was asked following question

Given the code fragments below, where the ellipsis (…) represents code that has not been disclosed to you:

class X { … };  class Y { public: explicit Y(const X& x); … }; 

what can you say about the compilation and execution of each of the following statements? Describe each of the operations that occur as this code executes.

Y func(Y y) { … }
X x;
Y y = func(Y(x));

I could not understand the question properly hence was not able to answer. if some one could explain me what answer was expected of me or share any link which I can go through, that would be really nice. Many Thanks.

Upvotes: 0

Views: 71

Answers (2)

hynner
hynner

Reputation: 1352

The line Y func(Y y) { … } can work only if Y has at least copy or move constructor, because otherwise you have no way of returning from the function or passing the parameter into it.

X x will only work if X has a default constructor.

Y y = func(Y(x)); will again only work if Y has copy or move constructor.

Here is an example.

Upvotes: 1

pstanisz
pstanisz

Reputation: 181

Perhaps ... means that there could be some code, which could affect the compilation and execution of code?

What is happening in code:

  • X default ctor is called,
  • func(Y(x)) is called: Y(x) ctor is explicitly called to create Y object from x.

Compilation of code depends (among other things) on X and Y constructors, ex.:

  • adding private default ctor to X prevents code from compilation,
  • adding private copy ctor to Y prevents code from compilation.

Upvotes: 1

Related Questions