xyz
xyz

Reputation: 8917

Operator overloading ( & -> )in C++

I have some basic questions on operator overloading in C++.

I am reading "Thinking in C++, volume 1" and it says that operators that can't be overloaded are member selection operator . , member dereference operator * . So it looks like other operators can be overloaded

Can I overload & operator? But won't this confuse compiler, if I implement it as prefix operator or does it then hide its default meaning?

In code to reference public members, I do sth like ptr -> data_member

I understand that compiler takes care of it and binds this reference with the data member, so this is not seen at all at runtime and -> does not come across as operator to run-time. Is this understanding correct?

As an aside, virtual concept exists only for member functions and not for data members, right? So at runtime if a Base pointer points to Derived class, I can not access members of Derived class from this pointer?

can I overload -> operator? But won't this confuse compiler, if I overload it as prefix operator

If question is not articulated properly, let me know.

are there some in-built operator overloading for each class by compiler etc

Upvotes: 3

Views: 945

Answers (3)

Alan
Alan

Reputation: 46823

Recall that operator& has two meanings: bit-wise and, and address of. Likewise, you can overload operator*, as multiplication, but not for pointers.

As for confusing the compiler, all modern C++ compilers will throw a compiler error when you do something that is ambiguous.

And just because you can overload an operator, doesn't mean you should; it's really easy to screw up some operators, and cause all kinds of really hard to find bugs.

Upvotes: 0

MGZero
MGZero

Reputation: 5963

overloading an operator is the same as overloading any other function. The compiler knows what to use based on the parameters you specified. So, no, the compiler won't get confused. You on the other hand, may get confused. This is one of the reasons why a lot of programmers say to avoid overloading operators (I disagree with this, depending on the case).

Upvotes: 5

Rocky Pulley
Rocky Pulley

Reputation: 23301

overloading operator -> is very useful, especially when creating a smart pointer class.

Upvotes: 9

Related Questions