Hi all,

I'm facing strange error. I defined a class:

class MyClass : public MyAbstractClass {
        public:
                MyClass() : myList(myList) {}
                ~MyClass() {}
                void AddList(list<MyObject>& myNewList) {
                        myList = myNewList;
                }

        private:
                list<MyObject>& myList;
};

And in the main I do:

// myObject is initialized here and is valid
// ...
list<MyObject> myNewList;
myNewList.push_back(myObject);
MyClass mc;
mc.AddList(myNewList);

Nice, that was a code. As you see, I create a list of objects in the main function - outside the class. Then I will be using MyClass mc, where the this list of objects is needed. I can't add the list in the constructor, because that is the request from 3d party developers. I must provide a method which will allow to set the list of objects. I've created AddList where I can assign myList reference to the new list.

The problem is constructor wants to initialize a reference, so I do fake initialization.
I don't like this, but compiler passes if I do so.

Next problem, program crashes while trying to execute AddList method. It says "Core dump".

Please, help me, poor newbie, what is wrong in my code? Why are these problems with reference as a class member. I have not have such neither python nor php. Also I do not want to use pointer to the list of objects, it is not a good time to use pointers.

Thankfully waiting for someone to clarify things.
Wish you well.

You've initialized myList to myList, creating a circular reference that then you cannot undo.

I think you will make your life easier if you use a pointer instead of a reference.

Thank you for noticing me! Yes, interesting, circular reference. But if I comment, compiler says me to initialize reference and then I don't know what about object can initialize it if not itself... So bad, that means references cannot be a members of a class if they are not initialized in the constructors? Very bad. However maybe this is a life. I think I should pass myNewList from the main to the constructor and no pointers.

Exactly. You have to initialize a reference and you don't have anything to which to initialize.

You are completely correct that a reference cannot be a member of a class unless every constructor initializes it. Part of the point of references is that they are always initialized.

If you want something that is similar to a reference but does not need to be initialized, you should use a pointer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.