Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize "ostream &out" in constructor, using "char *filename"

Tags:

c++

Please help me in initializing "out" in the constructor?

class logger {
        ostream &out;

        public:
        logger(char *str) : out(/*How do i construct an object using str*/) {}    

        template <typename T> void print(T &obj) { out << obj; }
};

This class will be defined globally for others to just call the print method

UPDATE: I am planning to have below setup, where user of class can 1) create a new ostream object if he does not have one. He can create but he have to manage it as well. So do not want to give the feature. 2) If he have already have one he can pass on like "cout/cerr". 3) If he passes nothing "cerr" will be assumed.

{

    ostream &out;

    public:
    logger() : out(cerr) {}         
    logger(ostream &o) : out(o){}
    logger(char *str) : out(/*How do i construct an object using str*/) {}

}

like image 717
rakesh Avatar asked Sep 01 '25 17:09

rakesh


1 Answers

There is no need for you to declare the stream as a reference, unless you want to be able to initialize from another stream. Something like this maybe:

class logger
{
    ofstream file;
    ostream &out;

public:
    logger(char *str) : file(str), out(file) {}
    logger(ostream &os) : out(os) {}

    // Other functions here, only using "out"
};
like image 130
Some programmer dude Avatar answered Sep 04 '25 06:09

Some programmer dude