I was going through constructors and while I was checking the copy constructor, my mind was set away.
I defined a class Scale and I was seeing how many times the copy constructor got called.
1 2 3 4
Scale nothing(const Scale &a)
{
return a;
}
During this function it gets called once. I assume it is during the return statement. Meaning that it returns a copy of a and not a itself.
Can anyone confirm this?
Also what if for no reason at all I want it to return a itself and not a copy? (I know it makes no sense but curiosity is kicking in, strongly)
When I tryed:
1 2 3 4
Scale& nothing(const Scale &a)
{
return &a;
}
C::B got angry at me and spitted this out:
1 2 3
o\Cpp\scales\main.cpp||In function 'Scale& nothing(const Scale&)':|
o\Cpp\scales\main.cpp|9|error: invalid initialization of non-const reference of type 'Scale&' from a temporary of type 'const Scale*'|
||=== Build finished: 1 errors, 0 warnings ===|
The problem of your function is that constness is lost. Make it return a const reference and it will work. If your function worked, const keyword would loose any purpose.
// for constructors
cout << "ctr_<object name here>:" << this << endl;
//for destructors
cout << "dtr_<object name here>:" << this << endl;
//for copy constructors
cout << "cctr_<object name here>:" << this << endl;
so that I can see which object sits where in memory. and I know when ctr/dtr/cctr calls are made.
it helps me a lot.. I can clearly see what's going on.