i have little query about () operator overloading. And my question is:
If u feel this is duplicate of any other question or not correct way to ask this means also comment over here. Thanks in advance....
Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes).
An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list. You must declare the overloaded = , [] , () , and -> operators as nonstatic member functions to ensure that they receive lvalues as their first operands.
Overloading operators cannot change the precedence and associativity of operators.
Operators that cannot be overloaded in C++ For an example the sizeof operator returns the size of the object or datatype as an operand. This is evaluated by the compiler. It cannot be evaluated during runtime. So we cannot overload it.
Question:
Does overloading parenthesis () effect constructor call?
No, it does not. The operator()
function can be used with an object. The constructors use the class/struct name. Example:
struct Foo
{
Foo() {}
int operator()(){return 10;}
};
Foo foo = Foo(); // The constructor gets called.
foo(); // The operator() function gets called.
Foo foo2 = foo(); // Syntax error. Cannot use the return value of foo()
// to construct a Foo.
int i = foo(); // OK.
It will not interfer with the constructor calls. The reason is that a constructor call works on the type or while constructing an instance, while operator()
works on a already constructed instance of the type.
Example:
struct A
{
A(int) {}
void operator()(int) {}
};
int main()
{
A(42); // calls the constructor A::A(int)
A a(42); // also calls A::A(int)
a(42); // calls A::operator(int)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With