user2023861
user2023861

Reputation: 8208

What is wrong with my operator<< overload code?

I am trying to overload the <<-operator for a class so that I can use std::cout with it. I've copied some code I found online to do this, but I can't get it to work.
I get an error that says:

error C2662: 'nspace::ElementCopy::name' : cannot convert 'this' pointer 
from 'const nspace::ElementCopy' to 'nspace::ElementCopy &'

The error is in the <<-operator implementation: (see my code comment)


Here is my header file, ElementCopy.h:

#pragma once
#include <string>
#include <iostream>

namespace nspace
{
    class ElementCopy
    {
        public:
            std::string name();
    };

    std::ostream& operator<< (std::ostream& stream, const ElementCopy& arg)
    {
        stream << arg.name(); //compiler error at this line
        return stream;
    }
}

And here is my short code file, ElementCopy.cpp:

#include "ElementCopy.h"

namespace nspace
{
    std::string ElementCopy::name()
    {
        return "string";
    }
}

I can't figure out this error. Why am I getting it? That operator overload doesn't have a "this" to speak of. How can I fix this?

Upvotes: 1

Views: 88

Answers (4)

Silent Control
Silent Control

Reputation: 612

Your name() method is not const, you might want to add const after its declaration.

Upvotes: 2

eduffy
eduffy

Reputation: 40262

Your argument arg is a const reference, but the ElementCopy::name method is non-const. Just add a const:

        std::string name() const;

Upvotes: 3

sehe
sehe

Reputation: 393934

You want to make the name() method const:

class ElementCopy
{
    public:
        std::string name() const;
};

This way, you will be allowed to call it on the const reference in your operator<<

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477640

The operator needs to be a free function, since the left argument is the stream, not your object. You typically achieve this by making it a friend inside your class:

friend std::ostream& operator<< (std::ostream& stream, const ElementCopy& arg)
{
    return stream << arg.name();
}

Since name() is a public member function, you can also declare this entire thing outside the class definition. The friend relationship is typically used to access private members conveniently without requiring getters just for the sake of the stream operator.

Upvotes: 1

Related Questions