Access shortcut for class property by operator overloading Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Access shortcut for class property by operator overloading without wasting too much if your time.

The question is published on by Tutorial Guruji team.

i trying to implement “access shortcut” for class property by operator overloading, but i can’t get it to work. Is it even possible ?

What i tried:

struct Fruit {
    float energy;
    float taste;
}

template<typename T>
class Value {
public:
    T val;
    T& operator->() { return val; }
}

Value<Fruit> apple;

// this work:
apple.val.energy = 0.5f;
cout << apple.val.energy << endl;

// this do not and i want this to work:
apple->energy = 0.5f;
cout << apple->energy << endl; 

Answer

It doesn’t work because operator-> must return a pointer, but yours does not. The compiler should have warned you about that, eg:

error: result of ‘operator->()’ yields non-pointer result

Try this instead:

template<typename T>
class Value {
public:
    T val;
    T* operator->() { return &val; }
};

Live Demo

We are here to answer your question about Access shortcut for class property by operator overloading - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji