Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading << operator C++ - Pointer to Class

class logger {
 ....
};

logger& operator<<(logger& log, const std::string& str)
{
    cout << "My Log: " << str << endl;
    return log;
}

logger log;
log << "Lexicon Starting";

Works fine, but i would like to use a pointer to a class instance instead. i.e.

logger * log = new log();
log << "Lexicon Starting";

Is this possible? If so what is the syntax? Thanks

Edit: The compiler Error is

error: invalid operands of types 'logger*' and 'const char [17]' to binary 'operator<<'
like image 253
user72523 Avatar asked Nov 27 '22 10:11

user72523


2 Answers

You'd have to dereference the pointer to your logger object and obviously check if it's not 0. Something like this should do the job:


  log && ((*log) << "Lexicon starting")

As a general aside, I would shy away from referencing objects like a logger (which you normally unconditionally expect to be present) via a pointer due to the uncertainty you get with a pointer, AKA is there an object or not?

like image 151
Timo Geusch Avatar answered Dec 05 '22 02:12

Timo Geusch


Here is the way:

logger * log = new log();
(*log) << "Lexicon Starting";
like image 32
decasteljau Avatar answered Dec 05 '22 03:12

decasteljau