dimanche 26 mars 2017

Constructor And Copy Constructor Behavior

The out put of this code is : C Called CC Called

#include <iostream>
using namespace std;


class test{
    private:
    public:
    test()
    {
        cout << "C Called" << endl;
    }

    test(test const &obj)
    {
        cout << "CC Called";
    }   

    test function()
    {
        return *this;
    }       
};
int main()
{
    test object;
    object.function();
}

The output of this code is C Called

#include <iostream>
using namespace std;


class test{
    private:
    public:
    test()
    {
        cout << "C Called" << endl;
    }

    test(test const &obj)
    {
        cout << "CC Called";
    }   

    test &function()
    {
        return *this;
    }       
};
int main()
{
    test object;
    object.function();
}

I would like to know, how is a new object returned after calling object.function(). I can not get the logic here that why copy constructor is being called with function() and why default constructor is called with &function().

Aucun commentaire:

Enregistrer un commentaire