Osama Ahmad
Osama Ahmad

Reputation: 2096

How to make an object that can be assigned a value but can't be read?

Output iterators can be assigned a value but their value can't be read. How can I make some object not readable but assignable like output iterators? I think that dereferencing an output iterator return an lvalue object that can be assigned a value. But, how can I get an lvalue object and not be able to read it?

Upvotes: 0

Views: 67

Answers (1)

bolov
bolov

Reputation: 75727

In C++ you can overload operator, including the assignment operator.

Here is an example where the operator= is overloaded to accept an integer:

class A
{
private:
    int val_;

public:
    A& operator=(int val)
    {
        val_ = val;
        return *this;
    }
};

My example is strictly academic. To be useful you need to have an actual use case for this.

My question is how to make *a = 3 a valid expression but int b = *a not a valid expression?

There are some ways. It all depends on the use case and what you want *a and *a = 3 to do. One way is to have operator* return a class like the above:

class X
{
public:
    A operator*() const
    {
        return A{};
    }
}

Upvotes: 1

Related Questions