0
votes

I tried to init a stringstream reference member with nothing, saying I wanted it to refer to null or just leave it un-initialized.

.hpp file

class Class{
    private:
        int n;
        stringstream& css;
    public:
        Class(int n);
        Class(stringstream& ss, int i);
    };

.cpp file

Class::Class(int n)
    :   n(n)    
{}

The compiler gives: Error 1 error C2758: 'Class::css' : must be initialized in constructor base/member initializer list

Do I have to initialize all the variables in the initialization list? Because I am not passing any stringstream reference to the constructor, how do I initialize it? Or if I don't want to initialize it, leave it blank. How do I do so?

1

1 Answers

3
votes

References members must be initialized. You don't want a reference, you want a pointer.

class Class{
private:
    int n;
    stringstream* css;
public:
    Class(int n);
    Class(stringstream& ss, int i);
};

Class::Class(int n)
    :n(n), css(nullptr)    
{}

Class::Class(stringstream& ss, int i)
    :n(i), css(&ss)
{}