Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does overloading parenthesis () effect constructor call?

i have little query about () operator overloading. And my question is:

  1. Does overloading parenthesis () effect constructor call?
  2. If it will effect means shall i do some pre/post processing before my constructor/destructor call?
  3. If question 2 is possible means what are the things shall i pre/post process and what should not?

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....

like image 553
nagarajan Avatar asked Feb 12 '15 06:02

nagarajan


People also ask

What does overloading the [] operator do?

Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes).

Can [] operator be overloaded?

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.

Which statement is false about operator overloading method?

Overloading operators cannot change the precedence and associativity of operators.

Which operator we Cannot overload?

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.


2 Answers

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.
like image 97
R Sahu Avatar answered Oct 09 '22 01:10

R Sahu


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)
}
like image 22
Daniel Frey Avatar answered Oct 09 '22 02:10

Daniel Frey