Question

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?

Was it helpful?

Solution

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<<

OTHER TIPS

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

        std::string name() const;

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top