Search code examples
c++ostreamistream

Constructor with ostream and istream parameters


I've got a question implementing a class constructor that has istream and ostream parameters. These values are to be used within the scope of the class. I am building a game that will ask questions and I want to use the istream parameter to collect the user input and the ostream to show things in the console.

class MyClass{

public:
    MyClass();
    MyClass(ostream& show, istream& userInput);
    ~MyClass();

    void anotherFunction(string name, string lastName);
    void executeProgram();

Can anyone explain a solution, and provide sample code, to make the scope of istream within the class accessible? How would I call this in the main class?

Edit: Hi and thank you for trying even i dont have clear output on this one.

What i am really looking for is to use this constructor as user interface of my program. This is a text based game which will accept 3 chars as options. I wanted to use this constructor to gather input. I hope that makes sense.


Solution

  • I don't see any particular problems here (and your question hasn't mentioned any). For example

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    class MyClass
    {
    public:
        MyClass() : _in(cin), _out(cout) {}
        MyClass(istream& in, ostream& out) : _in(in), _out(out) {}
    private:
        istream& _in;
        ostream& _out;
    };
    
    int main()
    {
        ifstream in("in.txt");
        ofstream out("out.txt");
        MyClass mc(in, out);
        ...
    }