Temporary object created by calling constructor
Hi, I was wondering if this idea I have is correct, I couldn't find an answer online :(
if i had a simple class
Code:
class Dog
{
Dog(x,y);
public:
void coolFunction(Dog) ;//Receives object of type Dog as parameter
private:
int x;
int y ;
}
So since the coolFunction(Dog Object) takes an object of type Dog, instead of declaring a
new object Dog dog1
and do this
Code:
coolFunction(dog1); ...//first method
I should be able to do this
Code:
coolFunction(Dog(4,4)) ; //second method
I believe that that the second method will create a temporary object in memory by calling the Vector(x,y) constructor,.. and when that copy is passed to the coolFunction(...) the object is then destroyed.
Can someone tell me if that is wrong or right?
Or if that is a good practice or idea..i know in C# the same concept is used or it is acceptable.
I promised to get back to this.
With better understanding of Copy Constructor.
I want to clarify the difference between doing this
Code:
a.coolFunction(Dog(4,4) ) ;
//and
a.coolFunction(b) ;
The compiler does not see Dog(4,4) as a already existing object, so therefore did not have any reason to invoke the copy constructor.
as a result it calls this constructor
Code:
Dog(int x, int y) : x(x), y(y)
{
std::cout << "Dog(int, int) of " << this << std::endl;
}
but for this piece of code a.coolFunction(b)
the compiler sees the reason to use a copy constructor to copy the already defined object.
That's an attempt to explain it to myself...