16

I overloaded the << operator of a class. How do I have to overload the operator if I want to use it on pointers, like the following?

class A {
    std::string operator<<(std::string&);
}

aInst << "This works";
aPointer << "This doesnt work";
aPointer->operator<<("Whereas this works but is useless");

I hope you can help me.

heinrich

4 Answers 4

24

You need to dereference the pointer first.

A *ptr = new A();
(*ptr) << "Something";

The only other way is the way you described above

Edit: Andre's solution below is workable as well, but like he said it may not be a good idea.

Sign up to request clarification or add additional context in comments.

Comments

14

First off, to stick with standard conventions, your operator<< should be declared like this:

class A {
    A& operator<<(const std::string&);
};

Now, technically, you could achiever part of what you want by implementing the following global function:

A * operator<< ( A * a, const std::string& s ) { (*a) << s; return a; }

This would allow statements such as:

string s = "this will be printed."; aPointer << s;
aPointer << string("this will be printed");

However, you won't be able to write the following:

aPointer << "this will not compile.";

In any case, writing such an operator would be confusing, at best. You should live with the more simple syntax of

(*aPointer) << "this will be printed.";

and write code that sticks to established conventions to allow others (and yourself, in a few weeks) to read your code.

Comments

3

You cannot do that. Operator functions are only considered for operands that have enumeration or class types among them.

You after all shift a pointer, but not a class. You need to explicitly say that you want to shift into a class object by dereferencing the pointer first.

1 Comment

@sbi correct. structs and unions are classes. Operator functions are considered when structs and unions are operands of a suitable operator, as for classes declared with the "class" class-key.
0

Normally there is no good reason doing that, because semantically operator << return reference to stream object. And technically you basically can't do that.

1 Comment

No, semantically operator<< should return the left-hand side argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.