Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class question

Tags:

c++

class

I am reviewing for my final, and I cannot figure out why this question is what it is.

Assume the following class declaration:

class Testing {
 public:
       Testing(int n);
       void Show(const Testing& w, int a = 10);
       int value;
 private:
       int DoThis();
 };

Assume the following lines of code are attempting in a main() program, and that x is of type Testing and has been propertly created.

x.Show(18); Legal or Illegal

The answer is legal, I understand that the 2nd parameter is not needed because of the = 10,but since 18 is not of type Testing isn't that an invalid parameter?

like image 260
dubyaa Avatar asked Dec 08 '10 21:12

dubyaa


2 Answers

Testing has a non-explicit constructor that takes an int. Therefore, an int can be implicitely converted to a Testing by constructing a temporary object.

Since Show takes a const Testing & (and not just a Testing &), you can pass a temporary to it. Finally, the second parameter is optional, so you don't have to specify a value for that.

This whole mechanism is what allows you do this, by the way:

void f(const std::string &str);
// ...
f("Hello");

Here, "Hello" is of type const char (&)[6], which decays to a const char *, but you can construct a std::string from a const char *, thus permitting the use of a const char * where a std::string parameter is needed.

Keep in mind that this constructs a temporary, and therefore is only valid for parameters that are passed by value or by const reference (it will fail for references). Also, the constructor must not be marked as explicit.

like image 195
Etienne de Martel Avatar answered Oct 17 '22 14:10

Etienne de Martel


There is a notion of automatic conversions in C++, called implicit conversion sequences. At most one conversion in such a sequence may be a user defined one, and calling a constructor for a temporary object is a user-defined conversion. It's ok to create a temporary here as that will be bound to the const-reference, and destroyed when the Show() call is complete.

like image 6
Martin v. Löwis Avatar answered Oct 17 '22 15:10

Martin v. Löwis