A simple example regarding definition of objects with a pointer to an object. We define an object A *a = new A(123.4);
and then another one with A *b = new A(*a);
What I do not understand is how exactly does this work for the b(pointer to) object? How does the copy constructor kicks in here and initializes the value to be the same as with object a? I thought that for this to work, we should declare a custom copy constructor in the class.
#include <iostream>
using namespace std;
class A {
public:
A(float v) { A::v = v; }
float v;
float set(float v) {
A::v = v;
return v;
}
float get(float v) {
return A::v;
}
};
int main() {
A *a = new A(123.4);
A *b = new A(*a);
cout << a->v << endl;
cout << b->v << endl;
a->v = 0.0;
cout << a->v << endl;
cout << b->v << endl;
b->v = 1.0;
cout << a->v << endl;
cout << b->v << endl;
return 0;
}
The program's output is:
123.4
123.4
0
123.4
0
1
Thanks in advance.