-1

what is the difference between

void A(const class1 a);

and

void A(const class1 &a);

in C++.

I am not able to differentiate these two.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

3

The main difference is that

A(const class1 a);

will create a local copy of a inside A which can be expensive (from both memory and computational point of view) while

A(const class1 &a);

will not create a copy.

Therefore passing the reference (2nd version) is usually the preferred way.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45
  • 1
    the first form is not necessarily more expensive all depends of the size of class1 if it is bigger than a reference so what you are saying is true otherwise it is not. – Venom Mar 22 '17 at 15:49
  • @basslo: That's correct and that's why I wrote "can be expensive". However in my experience it is unlikely that copying a class is less expensive (from memory consumption and computation point of view) than copying a reference. It does not only depend on the size of the class but mainly on what the copy constructor does. – Frank Puffer Mar 22 '17 at 15:55
  • Generally if `sizeof(type) <= sizeof(void*)` then passing by reference or value doesn't matter. – NathanOliver Mar 22 '17 at 15:57
  • @NathanOliver: What if the copy constructor does some complicated stuff? (I am not saying that a copy constructor *should* do this.) – Frank Puffer Mar 22 '17 at 16:02
  • @FrankPuffer There are certainly exceptions. Almost anything that stores a pointer should be passed by reference. – NathanOliver Mar 22 '17 at 16:26