0

what i have is two classes

//class A is a kind of config-class which have configuration details 
//for class B
class A{
//....
};

class B{
public:
B(A const& _a)
:a(_a){}

private:
A const& a;
};

till this point everything is fine.

now i want is a B::configure(A const& _a) function so that i can dynamically pass the reference of configuration class A to class B which shall be assigned to the member variable a. but i'm not able to change the member variable B::a as it is a const&.

what can be the work around?

i think @Seth Carnegie's approach is better, i should use a pointer to class A inside class B in this way:

 class B{
    public:
    B(A const& _a)
    :a(_a){}
    configure(A const& _a)
    { a = &_a; }    
    private:
    A const* a;
    };
1
  • You want to change the value of the object which the member reference refers to or you want the member reference to refer some another object? In either case, You can do only the former and not the later. Commented Aug 12, 2011 at 18:47

1 Answer 1

2

You cannot alter a reference after it's been initialized, whether it is const or not. The const just keeps you from making alterations to the variable that the reference refers to. So to change the variable after the instance has been constructed, you'll have to use pointers rather than references.

Your grammar was rather unclear, tell me if I misunderstood the question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.