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](https://stackoverflow.com/questions/4421706/operator-overloading?rq=1) 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?

Answer: 
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<<`
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.