Here is the code that i have
class A
{
public:
void Func1() const;
};
class B
{
public:
A* a;
void Func2() const
{
// do something with 'a'
}
};
void A::Func1() const
{
B b;
b.a = this;
b.Func2();
}
Now obviously this is giving me an error in the line, because I’m trying to convert from const to non-const.
b.a = this;
Is there any way to call Func2 without having to cast away the constness of this. Since Func2 is a const function anyways, it will not change this.
If
class Bis always going to work with*aas aconstobject then as others have said all it takes is to simply change the declaration toAt this point I should mention that the constness of
B::Func2is a red herring because it has absolutely no relation to the constness ofB::a. ThatB::Func2isconstmeans that it’s not allowed to change the value ofa; however, it is allowed to dereferenceaand mutate the resulting object.Now, if
class Bhas bothconstand non-constoperations with respect to*athen your class design needs to change. It would be much better if you switchedclass Bto use aconst A* aas above, and added anotherclass D : public Bthat encapsulates all the mutating operations. In addition,ashould be hidden behind a property setter; this allows you to do things likeWith this scheme both
BandDkeep independent, suitably typed pointers to the object to be accessed. IfsetAis called on aB, or on aDwith aconst A*parameter then onlyB::ais set. IfsetAis called on aDwith anA*, then bothB::aandD::aare properly set. This has become possible because by abstracting the member behind a setter you can then overload the setter on the constness of its parameter.