can member operators be virutal? does it make sense?

P

puzzlecracker

I have never seen this in practice and interested in its pros, or ever
existential (another words, standardized) possibility?


Thanks,

Sasha
 
A

Alan Woodland

puzzlecracker said:
I have never seen this in practice and interested in its pros, or ever
existential (another words, standardized) possibility?

As far as I know it's standardised - this works exactly as you'd expect:

#include <iostream>

class Foo {
public:
virtual void operator()(const int& a) { std::cout << "Foo" << std::endl; }
};

class Bar : public Foo {
public:
virtual void operator()(const int& a) { std::cout << "Bar" << std::endl; }
};

int main() {
Bar& b = *new Bar();
Foo& f = *new Foo();
Foo& fb = b;

b(10);
f(5);
fb(5);

return 0;
}

Alan
 
V

Victor Bazarov

puzzlecracker said:
I have never seen this in practice and interested in its pros, or ever
existential (another words, standardized) possibility?

I see nothing special in a member operator versus any other non-static
member function. Yes, absolutely, they can be virtual and it does make
sense to make them virtual if you need polymorphic behaviour.

Operators are nothing but syntactic sugar. Instead of, say, a function

...
virtual void doSomethingWith(int);
...

you could write

...
virtual void operator+(int);
...

.. And later, instead of writing

myobjectRef.doSomethingWith(42);

you would write

myojbectRef + 42;

Now, whether this makes sense is entirely problem-specific and cannot
be judged without any regard to what the purpose of the code is.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top