We know copy constructor is required either of the following scenario :
1) when we try to intialize one object using another object.
2) When we try to pass an object by value to a function or
3) when we return an object by value from a function.
I have written the following code just to test all the scenarios the first one worked well. Second one also didn't throw any error but it didn't give the desired result
When I am calling the function from main and passing an object by value to it copy constructor is not getting called same thing is happening when I am trying to return an object by value from a function as in the code.. please tell me where am I wrong?
Well you're returning a reference to that object, so the copy constructor is not going to be called. Change that function signature to return a copy, and then you'll see it being called.
Same goes for the func(). Change the parameter to be passed by value instead of by reference.
The technical reason is a temporary object cannot bind to a non-const reference.
A more intuitive (?) reason is because you don't want to be changing that object, and marking objects as const is a good defensive programming technique.