DragonClaw
DragonClaw

Reputation: 195

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;
}

Upvotes: 8

Views: 20584

Answers (5)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361254

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.

Upvotes: 9

Nitin Anand
Nitin Anand

Reputation: 9

You can't call a constructor of an already created object. What you are doing in code is, creating a temporary object. Compiler will report error if you do try to do this->multi(5,5).

Upvotes: 0

You can't call constructors like this. What your code does is create a new temporary instance of multi, which gets discarded immediately.

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

Upvotes: 1

Dima
Dima

Reputation: 39389

This doesn't 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 class multi, it has access to the private members, so it can just set a and b directly. You can get your expected output by rewriting multiply like this:

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

Upvotes: 1

Steve
Steve

Reputation: 1243

When you're calling the constructor multi(5, 5) you're actually creating a temporary object that is immediately destructed.

Upvotes: 2

Related Questions