C ++ class question

I am looking through my finale and I cannot understand 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(); }; 

Suppose that the following lines of code are used in the main () program and that x is of type Testing and has been correctly created.

x.Show(18); Legal or illegal

The answer is legal, I understand that the second parameter is not needed because of = 10 , but since 18 not of type Testing , is this not an invalid parameter?

+6
c ++ class
source share
4 answers

Testing has a non explicit constructor that accepts an int. Therefore, int can be implicitly converted to Testing by creating a temporary object.

Since Show accepts a const Testing & (and not just a Testing & ), you can pass a temporary one to it. Finally, the second parameter is optional, so you do not need to specify a value for this.

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

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

Here "Hello" is of type const char (&)[6] , which splits into a const char * , but you can build std::string from const char * , which allows you to use a const char * , where a std::string .

Keep in mind that this creates a temporary and, therefore, valid only for parameters that are passed by value or by reference const (for links will not). In addition, the constructor should not be marked explicit .

+16
source share

In C ++, there is the concept of automatic conversions called implicit conversion sequences . No more than one transformation in this sequence can be user-defined, and the constructor call for the temporary object is a user-defined transformation. It is normal to create a temporary one here, since it will be bound to a const reference and will be destroyed when the Show () call ends.

+6
source share

Since Testing has a constructor that accepts int , this c-tor is used to automatically assemble the Testing object for the first parameter. The code really ends up working:

 x.Show(Testing(18)); 
+5
source share

The constructor is here:

 Testing(int n); 

provides an implicit conversion from int to Testing , and this corresponds to the prototype for Show , with the first parameter being a Testing instance built from int 18, and the second parameter defaulting to 10.

If you prevent the implicit conversion as follows:

 explicit Testing(int n); 

the code will not compile.

+3
source share

All Articles