Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Class Constructor in Member Function

Here's a program, where I am trying to call the class constructor multi::multi(int, int), in the function void multi::multiply(). The output is

30

30

instead of expected

30

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;
}
like image 570
DragonClaw Avatar asked Jan 18 '13 15:01

DragonClaw


1 Answers

multi (5, 5);

It creates a temporary object, and gets destroyed by the end of the full expression. It doesn't do multiplication or printing.

To see the desired output, you can add a 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, prefer using member-initialization-list when defining constructors.

like image 73
Nawaz Avatar answered Sep 19 '22 01:09

Nawaz