-4

Here is my coding:

#include<iostream>
#include<string>
using std::endl;
using std::cin;
using std::cout;
using std::string;
using std::istream;
struct worker
{
   worker()=default;
   worker(istream &f);
   int data;
};
int main()
{
    worker a;
    cout<<a.data<<endl;
    system("Pause");
    return 0;
}
worker::worker(istream&f)
{
   read(f,*this);
}
istream&read(istream &f,worker&student)
{
   f>>student.data
   return f;
}

But when I debug,it warns me that I haven't initialized the element of a. I know that I need to input the data through worker(istream &f), but I don't know how to invoke the constructor function to initialize a.data.

karel
  • 189
  • 1
  • 8

1 Answers1

3

But when I debug, it warns me that I haven't initialized the element of a. I know that I need to input the data through worker(istream &f)

It's good that you realized the warning is really a problem. It's a warning from a syntactic point of view but it is an error from a semantic point of view.

The I know that part is ill-founded. You realized the need to initialize a.data but your approach to doing it is flawed.

but I don't know how to invoke the constructor function to intiallize a.data.

First of all, you cannot call constructor on already constructed object. Constructors are used only to construct objects, not to be called again on an already constructed object.

Secondly, use a different strategy to initialize the object. Remove the constructor worker(istream&) altogether. Use read on the already constructed object, such as:

int main()
{
    worker a;
    read(std::cin, a);
    std::cout << a.data << std::endl;
    return 0;
}

Further refinement.

Instead of read, use operator>>.

std::istream& operator>>(std::istream& f, worker& w)
{
   f >> w.data;
   return f;
}

Then, you can use:

int main()
{
    worker a;
    std::cin >> a;
    std::cout << a.data << std::endl;
    return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 4
    imho an answer should mention why OPs code is terribly broken. In general warningns are just warnings and not errors, but in this case the warning should be taken serious – 463035818_is_not_an_ai Jun 02 '17 at 17:17
  • @tobi303, thanks for the prod. – R Sahu Jun 02 '17 at 17:30
  • Your answer is valuable,but I still want to know why I can't use worker(istream &f) to explicitly intialize the value in the worker class. – karel Jun 02 '17 at 17:36
  • 1
    @karel, you can use `a = worker(std::cin);`, but it is not a good idiom to use. Please note that you still can't use `a.worker(std:::cin);`. – R Sahu Jun 02 '17 at 17:43