Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is function not called inside typeid?

Tags:

c++

Is a function not called inside a typeid? Consider the code below.

#include <iostream>
#include <typeinfo>
using namespace std;

int mul10(int &s)
{
    static int count = 1;
    cout << "Evaluating call " << count << endl;
    count++;
    s *= 10;
    return(s);
}

int main()
{
    int i = 5;
    cout << typeid(mul10(i)).name() << endl;
    cout << i << endl;
    return(0);
}

So here the output is

int
5

So clearly the value of i did not change and also the function mul10 was not actually called. Is that how typeid arguments evaluated?

like image 282
anupamb Avatar asked Oct 28 '15 22:10

anupamb


Video Answer


2 Answers

The operand of typeid is only evaluated if it is a glvalue of polymorphic class type. Since the return type of mul10, namely int, is not a polymorphic class type, the operand is not evaluated, meaning that mul10 is not called.

like image 132
Brian Bi Avatar answered Sep 30 '22 14:09

Brian Bi


If we go to the draft C++ standard it tell us that unless the expression glvalue of a polymorphic class type the result is based on the static type of the object. From section 5.2.8 [expr.typeid] with emphasis mine:

When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression. Lvalue-to-rvalue (4.1), array-topointer (4.2), and function-to-pointer (4.3) conversions are not applied to the expression. If the type of the expression is a class type, the class shall be completely-defined. The expression is an unevaluated operand (Clause 5).

like image 43
Shafik Yaghmour Avatar answered Sep 30 '22 12:09

Shafik Yaghmour