0

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?

nigong
  • 1,727
  • 3
  • 19
  • 33

1 Answers1

3

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)
{}
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • 2
    @LuchianGrigore: No, smart pointers are for ownership. This is a nullable reference. That's the one function left for which raw pointers are still useful. – Benjamin Lindley Nov 23 '12 at 20:30
  • @LuchianGrigore: If you make it a shared_ptr, you put a demand on your user that they must be using a shared_ptr too. They might just want to give you a reference to a local, non-dynamically allocated object. – Benjamin Lindley Nov 23 '12 at 20:34
  • But then don't you run the risk of remaining with a dangling pointer? – Luchian Grigore Nov 23 '12 at 20:35
  • @LuchianGrigore: Sure. You just have to treat the class like you would any reference or pointer. If you want an added measure of security, make it non-copyable. – Benjamin Lindley Nov 23 '12 at 20:39
  • I see. So a nullable reference member is a valid use-case for a raw pointer. Do you know of any further reading I can do on this? – Luchian Grigore Nov 23 '12 at 20:41
  • @LuchianGrigore: No, I don't. It's just a conclusion I came to a couple of years ago. I answered a question about it [here](http://stackoverflow.com/questions/4029970/c-what-are-scenarios-where-using-pointers-is-a-good-ideatm/4029988#4029988), and had it confirmed by a few other StackOverflowers whos opinion I respect. – Benjamin Lindley Nov 23 '12 at 20:48