S
SzH
Is it possible for a constructor to know if the object has been
initialised as a 'const' ot not? The example at at end of the message
illustrates what I would like to do.
I want to allow constructing a 'const Aref' from a 'const A' [1], so I
added another constructor to 'Aref'. But I don't want to allow creating
a non-const Aref from a 'const A' [2] to prevent accidental modification
of a const A by Aref::set().
I tried to make the second constructor 'const', but found that this is
impossible.
class A {
int data;
public:
A(int i) : data(i) { }
int read() const { return data; }
void set(int val) { data = val; }
};
class Aref {
A &ref;
public:
Aref(A &a) : ref(a) { }
// added this constructor to allow [1]:
Aref(const A &a) : ref(const_cast<A&>(a)) { }
// but it is not possible to declare a constructor const
// to disallow [2]!
int read() const { return ref.read(); }
void set(int val) { ref.set(val); }
};
int main() {
const A a = 1;
const Aref ar1 = a; // should be allowed [1]
Aref ar2 = a; // should be illegal [2]
}
initialised as a 'const' ot not? The example at at end of the message
illustrates what I would like to do.
I want to allow constructing a 'const Aref' from a 'const A' [1], so I
added another constructor to 'Aref'. But I don't want to allow creating
a non-const Aref from a 'const A' [2] to prevent accidental modification
of a const A by Aref::set().
I tried to make the second constructor 'const', but found that this is
impossible.
class A {
int data;
public:
A(int i) : data(i) { }
int read() const { return data; }
void set(int val) { data = val; }
};
class Aref {
A &ref;
public:
Aref(A &a) : ref(a) { }
// added this constructor to allow [1]:
Aref(const A &a) : ref(const_cast<A&>(a)) { }
// but it is not possible to declare a constructor const
// to disallow [2]!
int read() const { return ref.read(); }
void set(int val) { ref.set(val); }
};
int main() {
const A a = 1;
const Aref ar1 = a; // should be allowed [1]
Aref ar2 = a; // should be illegal [2]
}