Constructor class call in member function

Here is the program in which I am trying to call the constructor of the multi::multi(int, int) class, in the void multi::multiply() function. Output signal

thirty

thirty

instead of the expected

thirty

25

Why?

 #include <iostream.h> class multi{ private: int a; int b; public: multi(int m, int n){ a = m; b = n; } void multiply(){ cout << "\n\n" << a*b; multi (5, 5); cout << "\n" << a*b; } }; main(){ multi x(5,6); x.multiply(); return 0; } 
+4
source share
5 answers
 multi (5, 5); 

Creates a temporary object and is destroyed to the end of the full expression. It does not perform multiplication or printing.

To see the desired output, you can add the reset() member function to your class:

 class multi{ private: int a; int b; public: multi(int m, int n) : a(m), b(n) {} //rewrote it void reset(int m, int n) { a = m; b = n; } //added by me void multiply(){ cout << "\n\n" << a*b; reset(5, 5); //<-------------- note this cout << "\n" << a*b; } }; 

By the way, we prefer to use member-initialization-list when defining constructors.

+7
source

When you invoke the multi(5, 5) constructor, you are actually creating a temporary object that immediately collapses.

+1
source

This does not work, because multi(5, 5); creates a temporary object of class multi , which is immediately destroyed, because it is not used for anything

Since multiply() is a member function of the multi class, it has access to private members, so it can just set a and b directly. You can get the expected result by rewriting multiply as follows:

  void multiply() { cout << "\n\n" << a*b; b = 5; cout << "\n" << a*b; } 
0
source

You cannot call constructors like this. Your code creates a new temporary instance of multi , which is immediately discarded.

Once an object is constructed, you cannot call its constructor again. Create an assign() function or something similar in your class.

0
source

You cannot call the constructor of an already created object. What you do in the code is creating a temporary object. The compiler will report an error if you try to do this-> multi (5.5).

0
source

All Articles