0

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.

BugShotGG
  • 4,432
  • 6
  • 42
  • 60
  • The compiler generated a copy constructor for you. It will perform a shallow copy of member variables, which is good enough in your case. – AndyG Apr 29 '15 at 12:35
  • Every class has a copy constructor, whether or not you define one yourself. – Kerrek SB Apr 29 '15 at 12:42
  • @KerrekSB If AndyG's answer and the comment below his answer is correct, what you are saying is not true... or I am misunderstanding something – 463035818_is_not_a_number Apr 29 '15 at 14:24
  • @tobi303: It depends how pedantic you want to get. A copy constructor is always declared (which is what I meant when I said "has"). If it is not user-defined, it is implicitly defined when it is first odr-used, and it may be defined as deleted. – Kerrek SB Apr 29 '15 at 16:37

1 Answers1

2

The compiler generated a copy constructor for you. It will perform a shallow copy of member variables, which is good enough in your case.

From Wikipedia:

Special member functions in C++ are functions which the compiler will automatically generate if they are used, but not declared explicitly by the programmer. The special member functions are:

  • Default constructor (if no other constructor is explicitly declared)
  • Copy constructor if no move constructor or move assignment operator is explicitly declared. If a destructor is declared, generation of a copy constructor is deprecated.
  • Move constructor if no copy constructor, move assignment operator or destructor is explicitly declared.
  • Copy assignment operator if no move constructor or move assignment operator is explicitly declared. If a destructor is declared, generation of a copy assignment operator is deprecated.
  • Move assignment operator if no copy constructor, copy assignment operator or destructor is explicitly declared.
  • Destructor
Community
  • 1
  • 1
AndyG
  • 35,661
  • 8
  • 94
  • 126