nagrik wrote:
Hello group,
Last week I picked up a thread, which pointed out that if a copy
constructor is created with pointers
instead of reference, there is a danger of it going in infinite
recursion.
Thats not a danger since a ctor with a pointer is not a copy ctor, its
a parametized ctor.
A pointer is not an object. A reference, however, is an object.
A pointer is just an address, it may or may not point to anything.
>
My observation:
1. Compiler does not complain.
2. Does not go in infinite recursion.
3. Does not work the way it should have worked.
Following is my code.
using namespace std;
#include <iostream>
class B {
public:
B() {cout << "inside B default" << endl;}
B(B* cp) {cout << "inside B pointer copy" << endl;}
Thats not a copy ctor. see below.
>
};
int main(void) {
B* b = new B;
B* some = b;
return 0;
}
The program should print
inside B default
inside B pointer copy
How? All i see is a ctor + a pointer being copied.
>
Instead it prints only
inside B default.
Any ideas, comments.
You confusion is partly because you aren't labelling your pointers
appropriately. The "variable" b above is not an instance of B, its just
a dumb pointer. The same goes for some.
The first line in main() invokes a default ctor.
Nowhere else is construction of any kind taking place.
Copying a pointer does not invoke an object ctor of any kind.
Now consider the class below. It has:
a) a default ctor
b) a parametized ctor - which doesn't do anything usefull with the
parameter
c) a copy ctor
d) a d~tor
Follow the output.
#include <iostream>
class B
{
public:
B() {std::cout << "B()\n";}
B(B* p) {std::cout << "B(B* p)\n";}
B(const B& copy) {std::cout << "copy B()\n";}
~B() {std::cout << "~B()\n";}
};
int main()
{
B* p(new B); // exactly the same as B* p = new B, invoking the
default ctor
B another(*p); // what is *at* p is being passed, hence a copy!
// p is a pointer, *p is not a pointer
B instance(p); // invoking a parametized ctor B( B* )
B* p_b = &instance; // nothing happened, a dumb pointer gets an
address
B* p_b2 = p_b; // same
B* p_b3 = p_b2; // same
delete p; // required
return 0;
}
/*
B()
copy B()
B(B* p)
~B()
~B()
~B()
*/