Karedia Noorsil
Karedia Noorsil

Reputation: 470

How to call two argument constructor in istream& operator?

class base
{
    int a, b;
public:
    base(int a, int b);
    {
        a = a;
        b = b;    
    }
}

istream& operator>>(istream& is, base& no)
{
    int area, local;
    cout << "Area Code     : ";
    is >> area;
    cout << "Local number  : ";
    is >> local;
    // call two argument constructor;
    return is;
}

I've tried base(area,local); but after execution the values changes back to 0

I've also tried no(area,local); that too doesn't work...

Upvotes: 0

Views: 111

Answers (3)

Zac Howland
Zac Howland

Reputation: 15870

What you are describing is not a constructor; it is an insertion operator (operator>>).

For your class base, you could call it like so:

base b;
std::cin >> b;

And your operator would be implemented as

istream& operator>>(istream& is, base& no)
{
    cout << "Area Code     : ";
    is >> no.area;
    cout << "Local number  : ";
    is >> no.local;
    // call two argument constructor;
    return is;
}

Upvotes: 1

Paweł Stawarz
Paweł Stawarz

Reputation: 4012

Inside your constructor, you do:

base(int a, int b);
{
    a = a;
    b = b;    
}

Which just assigns the parameters to themselves, not to the member variables of the object. In order to change the member variables, you have to do:

base(int a, int b)
{
    this->a = a;
    this->b = b;    
}

The syntax for calling it is no = base(area, local);. You can also need an assigment operator if your IDE won't generate it for you. It's probably smart enough to do it, but just giving you a heads up.

Upvotes: 0

Phil Miller
Phil Miller

Reputation: 38138

You could write it as

no = base(area, local);

Or, if you make the operator>> a friend of your base class, then you could modify the individual reads to be

is >> no.area;
is >> no.local;

Upvotes: 1

Related Questions