Functions with pointer arguments in C++

80 views Asked by At

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 :-)

2

There are 2 answers

0
TartanLlama On BEST ANSWER
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.

0
user5024170 On

compiler will generate copy constructor and assign value function, if you don't want to use these 2 function. you need declare it in private scope of class

private:
     Item(const Item&);
     Item& operator=(const Item&);