Moule Lin
← All notes

Function-like Classes

#include<iostream>

class temporary{
public:
    temporary(){
            std::cout << "temporary ctor" <<std::endl;
    }
    ~temporary(){
        std::cout << "destory"  <<std::endl;
    }
    void fun(){
        std::cout << "This is function output"  <<std::endl;
    }

};
int main(){
    
    temporary ().fun();
    return 0;
}

output:

temporary ctor
This is function output
destory
Integer inte= Integer(5); //initialize an object with an unnamed temporary object
class Integer
{
public:
    Integer(int i):m_val(i){}
    ~Integer(){}
private:
    int m_val;
};
 
void testFunc(Integer itgr)
{
    //do something
}

int  i = 10;
testFunc(i);

A temporary object is created and passed as the argument to testFunc.
Integer Func()
{
    Integer itgr;
    return itgr;
}
 
int main()
{
    Integer in;
    in = Func();
}

Why we need function-like class?