Hey guys i have this code Animal.h:
/*
* Animal.h
*
* Created on: May 27, 2015
* Author: saif
*/
#ifndef ANIMAL_H_
#define ANIMAL_H_
#include <iostream>
using namespace std;
class Animal {
int age;
public:
Animal();
Animal(const Animal & rhs);
Animal addTo();
virtual ~Animal();
};
#endif /* ANIMAL_H_ */
Animal.cpp:
/*
* Animal.cpp
*
* Created on: May 27, 2015
* Author: saif
*/
#include "Animal.h"
Animal::Animal()
:age(0)
{
}
Animal::Animal(const Animal & rhs)
:age(rhs.age)
{
cout << "copy constructor activated" << endl;
}
Animal Animal::addTo()
{
Animal ret;
ret.age = 5;
return ret;
}
Animal::~Animal() {
cout << "NO not done, destructing.."<< endl;
}
main.cpp
#include <iostream>
using namespace std;
#include "Animal.h"
int main() {
Animal a;
Animal b = a.addTo();
cout << "done" << endl;
return 0;
}
Output:
done
NO not done, destructing..
NO not done, destructing..
Expected output:
copy constructor activated
done
NO not done, destructing..
NO not done, destructing.
Or even:
copy constructor activated
copy constructor activated
done
NO not done, destructing..
NO not done, destructing.
Because I read from books and other resources that when we return function by value or give parameters to function by value it calls copy constructor because it makes a temporary copy, and also I have in main a situation (line 6) where copy constructor must be activated, but it didn't.. why?