Value Based Semantics

You need to know that, if you do not understand value-based semantics, you are not a C++ programmer.  Naturally, there is much more you must know to become a C++ programmer, but value-based semantics is one of the essentials. Further, value-based semantics is non-trivial.

Having said that...

Lets start with what value-based semantics is.  Value-based semantics are semantics that allow our classes to behave like built in primitive types. For example, if we design a rational class (a rational class represents fractions 1/2, 3/4, etc.) and we want it to have value-based semantics, we design it so that it behaves like primitive types. So, with class rational we expect to be able to write code like:

   rational r1, r2(1,2), r3(r2);
   r1 = r2 + r3;
   r1 = r2 / r3;
   if(r2 == r3)
      cout << " r2 is equal to r3 " << endl;

The following program shows that the primitive type int supports all of these things and will compile and execute with no errors or warnings. (in MSVC++ 6.0)

#include <iostream>
using namespace std;

void myFunction(int i){
	cout << " i0++ is " << ++i << endl;

void main(){
   int i0=4, i1, i2(3), i3(i0);
   i1 = i2 + i3;
   i1 = i2 / i3;
   if(i2 == i3)
      cout << " i2 is equal to i3 " << endl;
   cout << " i0 is " << i0 << endl;

So what is required here? 

In general value-based semantics require at least:

Why is this called value-based semantics? You need to recall that when we pass parameters to a function or method and a copy of the value is made, we are using a pass by value mechanism.  The implication of this is that, for an object, a copy of the object must be made.  So, a class that allows this type of passing is said to have value-based semantics. This is a bit of a misnomer, because value-based semantics actually includes several aspects of object behavior.

We have two options for how copies will be made.

        1) Provide no code and allow the compiler to create the copy

        2) Provide a copy constructor.

If we provide no code and the compiler can create a copy; it will create a bit-by-bit copy.  This means that if memory allocation occurs in construction of our class, the object copy will NOT have its own memory allocation, but will use the storage of the original object. This is said to be a shallow copy.

See my CIT505 links for discussions of the copy constructor and the overload of the assignment operator.