0

I have the following code and am trying to understand the copy constructor and assignment operator. I can follow along all the way to where this code prints out p0. I'm confused per comments in code, why the default constructor and copy constructor are not called. Appreciate any guidance on why this is happening? Thanks

#include <iostream>

class X {
public:
  X();
  X(const X &s);
  X &operator=(const X &s);
};

X::X()
{
  std::cout << "X()" << '\n';
}

X::X(const X &s)
{
  std::cout << "X(cc)" << '\n';
}

X& X::operator=(const X &s)
{
  std::cout << "X(ao)" << '\n';
  return *this;
}

int main(int argc, char *argv[])
{
  /* call empty () cons */
  X s1, s2;

  /* both same call ao */
  s2 = s1;
  s2.operator=(s1);

  /* call cc */
  X s3(s1);
  std::cout << "p0" << '\n';
  X s4 = X();
  /* why is default constructor and copy constructor not called? */
  std::cout << "p1" << '\n';
  X s5(X());
  /* why is default constructor not called? */
  std::cout << "p2" << '\n';
  X s6();

  return 0;
}

g++ test50.cc && ./a.out
X()
X()
X(ao)
X(ao)
X(cc)
p0
X()
p1
p2

UPDATE: per comments this does look like: https://en.wikipedia.org/wiki/Most_vexing_parse

notaorb
  • 1,944
  • 1
  • 8
  • 18

0 Answers0