user9196120
user9196120

Reputation: 401

Constructing an object as part of ostream output

For a class declaration as below:

class A{
public:
A(int);
~A()
private:
int a;
};

And a constructor definition as follows:

A::A(int i){
 a = i;
 cout << a << endl;
}

I would like to do something like this from main():

int main(){
int i;
//user input for value
//stored inside i
cout << "The value is " << A obj(i);
return 0;
}

I now get the following error for the above code in main():

error: 'A' does not refer to a value

What is the cause of this error?

Upvotes: 1

Views: 64

Answers (3)

Tincu Stefan Lucian
Tincu Stefan Lucian

Reputation: 16

You need to first output the message "The value is " on first code line. On the second code line you create the object obj of type A which will output the i.

int main()
{
    int i;
    cout << "The value is ";
    A obj(i);
    return 0;
}

Upvotes: 0

Aganju
Aganju

Reputation: 6405

You cannot have a declaration in the middle of another line.

What you can do is create an A on the fly with casting (A) i, or simply A(i), this will cast the int i into an A, and then send it to cout. The temporary A object is then directly discarded.

If you want to keep it, you have to declare a name for it, in its own statement.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726649

You cannot declare obj and output it on the same line. If you want obj to remain available after printing, do this:

A obj(i);
cout << "The value is " << obj;

Otherwise, skip obj in favor of a temporary object:

cout << "The value is " << A(i);

Upvotes: 1

Related Questions