Search code examples
c++functionpointersconstructorampersand

Functions with pointer arguments in C++


I'm having some difficulties in understanding some aspects of functions with pointers. Here is the code I'm running:

#include <iostream>

using namespace std;

class Item
{
public:

    Item(Item * it)
    {
        data = it->data;
    }

    Item(int d)
    {
        data = d;
    }

    void printData()
    {
        cout << data << endl;
    }

private:
    int data;
};

int main()
{
    Item i1(79);
    Item i2(i1);

    i1.printData();
    i2.printData();
}

This code works, the problem is that I don't understand why! The constructor for the Item class needs a pointer, but I'm passing an object to it, not a pointer to the object. The code also works if I actually pass the pointer by using:

Item i2(&i1);

So, is the ampersand optional? Does the compiler recognise that I meant to pass a pointer instead of the actual object and take care of that by itself? I expect a compiling error in this kind of situation. I get very frustrated if my code works when it shouldn't :-)


Solution

  • Item i2(i1);
    

    This works because it is not calling your user-defined constructor which takes a pointer, it is calling the implicitly generated copy-constructor which has the signature:

    Item (const Item &);
    

    If you don't want this to be valid, you can delete it (requires C++11):

    Item (const Item &) = delete;
    

    If your compiler doesn't support C++11, you can just declare it private.