Operators That Cannot Be Overloaded
C++ allows many operators to be overloaded, but not all of them.
Some operators are too closely connected to the compiler's grammar, memory model, or type system. Allowing programmers to change them would make code confusing or unsafe.
Operators That Cannot Be Overloaded
| Operator | Name | Why it cannot be overloaded |
|---|---|---|
. |
dot/member access | It is fundamental for accessing real class members. |
:: |
scope resolution | It is used by the compiler to resolve namespaces and class scopes. |
?: |
ternary conditional | It has special conditional evaluation behavior. |
.* |
pointer-to-member access | It depends on built-in member access rules. |
sizeof |
size operator | It is handled by the compiler for memory layout. |
typeid |
type identification | It is part of C++ runtime type information. |
alignof |
alignment query | It is a compile-time type property. |
noexcept |
exception check | It is a compile-time language feature. |
Why These Restrictions Exist
Operator overloading should improve readability for user-defined types. It should not change the core grammar of C++.
For example, if . could be overloaded, this simple expression could become confusing:
student.name
The reader would not know whether name is really a member or the result of hidden custom logic.
Operators That Can Be Overloaded But Need Care
Some operators can be overloaded, but they should be used carefully.
| Operator | Warning |
|---|---|
&& and || |
overloaded versions do not preserve normal short-circuit behavior in the same way |
, |
often makes code harder to read |
& |
can confuse readers because it normally means address-of |
-> |
useful for smart pointer-like classes, but advanced |
Viva Answer
Some operators cannot be overloaded because they are part of the fundamental syntax, compile-time behavior, or type system of C++. Examples include ., ::, ?:, .*, sizeof, typeid, alignof, and noexcept.
Quick Check
- Can the dot operator be overloaded?
- Why can
sizeofnot be overloaded? - Should every overloadable operator be overloaded?