Say I have a class Foo
class Foo {
}
I do following assignments:
Foo *ptrFoo=new Foo();
Foo &ref=*(ptrFoo); //question 1
Foo afoo=*(ptrFoo); //quesion 2
My questions :
1) When assignming to “&ref” what internally happens in-terms of memory?
Is it just assigning the memory address of “ptrFoo” to “ref” ?
2) When assigning to “afoo”, what happends? Does it call copy-constructor?That means memory is allocated for two Foo objects? ie, “afoo” and previously assigned memory for “ptrFoo” ?
3) Say I have a method called “void methodBar(const Foo &instance)”
If I pass “ptrFoo” as:
methodBar( (*preFoo));
whats the significant of “const” here ?
That depends on your platform, compiler, and compiler settings. Your compiler may just generate a synonym for the dereferencing. Because a reference may not be redefined there’s no reason a compiler really needs to allocate any memory for the variable.
Yes, the contents of the
Foostored in dynamic storage are copied (using the copy constructor) to the instance ofFooin automatic storage. There’s no dynamic allocation going on here though; theaFooinstance would get created just as simply if there were no assignment. For instance,Foo aFoo;.constin that position means that while the item is passed by reference, the method which declared that referenceconstis not allowed to modify the instance the reference references.