0

I would like to have a member variable of a class which stores the input stream depending on a string entered by the user. eg.

#include <string.h>
#include <iostream>
#include <fstream>

class myInput {
public:
    myInput(std::string file_name);
    myInput() = delete;

protected:
    std::istream& in_data;
};
 
myInput::myInput(std::string file_name)
    : in_data((file_name == "-") ? std::cin : std::ifstream(file_name)){}

void main() {
    myInput("file.txt");
}

However I am receiving the following errors

error: use of deleted function ‘std::basic_istream<_CharT, _Traits>::basic_istream(const std::basic_istream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]’
error: ‘std::basic_istream<_CharT, _Traits>::basic_istream(const std::basic_istream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]’ is protected within this context

I have also tried creating the ifstream object separately and assigning that to in_data, but encounter similar problems. Why is this?

base12
  • 125
  • 1
  • 10
  • I believe you are missing initialization for in_data in your myInput constructor... refer to the accepted answer here: https://stackoverflow.com/questions/5966698/error-use-of-deleted-function – lucasreta Feb 22 '21 at 05:41
  • Hint: you have to store the **object** ifstream if the case the string is not "-". – user202729 Feb 22 '21 at 06:22

2 Answers2

1

std::istream does not allow you to do something like in_data = std::cin or in_data = std::ifstream("file.txt") as the assignment operator is deleted.

An alternate solution is to use a pointer to std::istream.

class myInput {
public:
    myInput(std::string file_name);
    virtual ~myInput() { if (bIsHeapAllocated) delete in_data; } // delete the heap allocation if done.
    myInput() = delete;

protected:
    std::istream* in_data = nullptr;
    bool bIsHeapAllocated = false;    // You can make this a private member if you don't want your inherited classes knowing this.
};

myInput::myInput(std::string file_name)
{
    if (file_name == "-")
        in_data = &std::cin;
    else
        in_data = new std::ifstream(file_name), bIsHeapAllocated = true;    // Allocate the ifstream in heap
}
D-RAJ
  • 3,263
  • 2
  • 6
  • 24
0

Include the #include <iostream> header file first in your program it shouldn't be on the second line

iamdhavalparmar
  • 1,090
  • 6
  • 23
  • 1
    While this is indeed an issue with the code of op, it doesn't solve the problem. – user202729 Feb 22 '21 at 04:57
  • This doesn't solve the issue. Also my code (in the full implementation) is auto-formatted. It actually puts `iostream` after `fstream` for some reason – base12 Feb 22 '21 at 05:01
  • 1
    It's a good practice to include `iostream` at first, but if not added at first, it doesn't cause any error either. – Abhishek Dutt Feb 22 '21 at 05:06