1

I am confused over the behavior of constructor in this code.

class htc {
  public:
  htc() { std::cout << "HTC_FOO_CONSTRUCTOR" << std::endl ;}
  htc(const htc&) { std::cout << "HTC_BAR_CONSTRUCTOR" << std::endl;};
};

int main() 
{
  htc one; // This outputs HTC_FOO_CONSTRUCTOR
  htc two(); // This outputs nothing 
  htc three(one)
}

Couple of questions whats the meaning of using brackets in htc two() mean? & in constructor htc(const htc&) there is no parameter name is this ok? If yes whats the use of an such constructor?

K_TGTK
  • 765
  • 1
  • 8
  • 24

1 Answers1

1

You're declaring a function, not calling a constructor:

class htc {
  public:
  htc() { std::cout << "HTC_FOO_CONSTRUCTOR" << std::endl ;}
  htc(const htc&) { std::cout << "HTC_BAR_CONSTRUCTOR" << std::endl;};
};

int main() 
{
  htc one; // This outputs HTC_FOO_CONSTRUCTOR
  htc two(); // Function declaration
  htc three(one); // Outputs HTC_BAR_CONSTRUCTOR
}

clang also triggers this explicative warning:

warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]

Sidenote: not sure if you were referring to the dynamic allocation with default/value initialization.

For your second question: it is perfectly acceptable to have a constructor with no formal argument name (it is often done to conform to an interface although you don't really need that parameter). You might want to do something else when such a situation (i.e. copy construction) is detected.

Marco A.
  • 43,032
  • 26
  • 132
  • 246