1

I was some misunderstanding about default operator definition(by compiler).

I have small class:

class Q
{
public:
    Q() {};
    Q(int i) { x = i; };
    ~Q() {};
    void print() { cout << x << endl; };
    Q& operator * ()
    {
        cout << "operator *\n";
        return *this;
    };
    const Q& operator * () const
    {
        cout << "operator *\n";
        return *this;
    };
private:
    int x;
};

And i'm doing this whit it:

int main()
{
    Q* obj_p = new Q(1);
    Q obj = *obj_p;
    obj.print();
    return 0;
}

I expected to see operator *, before 1. But I saw only print() method result.

What does it mean? That I don't need to overload operator * - it's compiler work or that I do overloading somehow wrong?

Thanks.

3 Answers 3

4

obj_p is a pointer. You have not overloaded (and cannot do it anyway) the de-reference operator for a pointer. To invoke your overload, you need to act on an instance:

Q obj;
*obj;
Sign up to request clarification or add additional context in comments.

2 Comments

And can you tell me, please: what about 'new' operator.<br> Should I overload it(in simple cases, not so simple like that, but still)? Or compiler will allocate exactly as much memory for my class as I need?
@KirillTimofeev You need to overload the operator new function if, and only if, your class needs some special allocation (typically, a pool allocator, or some such). Such cases are rare.
1

There's no user-defined operator called - obj_p is a pointer, not an object, so the built-in dereference operator is called.

To complete juanchopanza's answer, you can call your operator on a pointer like so:

Q* obj_p = new Q(1);
Q obj = obj_p->operator*();

Comments

0

You use your '*' operator on Q pointer but you should use on Q objects. if you try *(*obj_p) you will see.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.