Beakie
Beakie

Reputation: 2009

Passing a const pointer... do I need to do it?

I have a struct of Foo:

struct Foo
{
};

I have a struct of Bar:

struct Bar
{
};

They are handled by 2 more structs which maintain (add/remove) a pointer array of each:

struct FooContainer
{
    Foo** FooList;

    // add(), remove() etc
};

struct BarContainer
{
    Bar** BarList;

    // add(), remove() etc
};

Now, what I WANT is another struct called Baz which links (in a one-to-many fashion) Foo to Baz. I can't (for reasons not explained here) refer to them by index, it must be by pointer/reference.

Something like this:

struct Baz
{
    Foo* foo;
    Bar* bar;
};

If I wanted to add a constructor to Baz which took these non-const pointers, how would I do it?

Baz should allow me to change which instance of Foo and Bar it points to... so it's pointers don't want to be const.

Do I pass the pointers into the constructor as const and then do something with them as I would if I were passing a reference to a struct? I then get issues with trying to set the value of a non-const pointer to a const pointer.

I hope this question makes sense...

Edit: Should I use reference instead of pointer?

Upvotes: 1

Views: 82

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

Baz should allow me to change which instance of Foo and Bar it points to... so it's pointers don't want to be const.

That is correct, you don't want to store constant pointers. However, it does not prevent you to store pointers to const, which is not the same thing.

This sounds confusing, so here is an illustration using your Baz example:

struct Baz
{
    const Foo* foo;
    const Bar* bar;
    Baz(const Foo* newFoo, const Bar* newBar) : foo(newFoo), bar(newBar) {}
    void setFoo(const Foo* newFoo) { foo = newFoo; }
    void setBar(const Bar* newBar) { bar = newBar; }
};

everything is going to compile fine: it's Foo and Bar pointed to by foo and bar that are const, not the pointers themselves, which leaves you free to change the pointers as you wish.

This, on the other hand, is not going to compile:

struct Baz
{   // Note how const has moved to the other side of the asterisk
    Foo* const foo;
    Bar* const bar;
    Baz(Foo* newFoo, Bar* newBar) : foo(newFoo), bar(newBar) {}
    void setFoo(Foo* newFoo) { foo = newFoo; } // BROKEN!!!
    void setBar(Bar* newBar) { bar = newBar; } // BROKEN!!! 
};

Now the pointer, not the "pointee", is const, preventing you from changing foo or bar members.

Upvotes: 3

Related Questions