Functions with pointer pointers in C ++

I am having some difficulty understanding some aspects of pointer functions. 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 I don't understand why! The constructor of the Item class needs a pointer, but I am passing it an object, not a pointer to an object. The code also works if I actually pass the pointer using:

Item i2(&i1);

      

So the ampersand is optional? Does the compiler recognize that I wanted to pass a pointer instead of an actual object and take care of that itself? I expect a compilation error in a situation like this. I get very frustrated if my code works when it shouldn't :-)

+3


source to share


2 answers


Item i2(i1);

      

This works because it doesn't call your user-defined constructor, which takes a pointer, it calls an implicitly instantiated constructor that is signed:

Item (const Item &);

      



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

Item (const Item &) = delete;

      

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

+6


source


the compiler will generate a copy constructor and assign a value function if you don't want to use those 2 functions. you need to declare it in a private class scope



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

      

+2


source







All Articles