In C++, object constructors cannot be const-qualified.
But - can the constructor of an object of class A
know whether it's constructing a const A
or a non-const A
?
Motivated by a fine point in the discussion regarding this question.
Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile .
A const object can be created by prefixing the const keyword to the object declaration. Any attempt to change the data member of const objects results in a compile-time error. When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object.
Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword.
What is constructor? A constructor is a special type of member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object (instance of class) create. It is special member function of the class because it does not have any return type. How constructors are different from a normal member ...
Another way to look at it is that const means the method doesn't mutate your object's state. A constructor's sole purpose is to initialize an object's state to be valid (well hopefully anyway - any constructors with side effects should be ...carefully evaluated).
If this constructor were not a const method itself, then the internal pointers and such would also not be const. Therefore, it could not set const values into those non-const members.
Just because Image is const in your imaginary constructor doesn't mean that what m_data points to is. You'd end up being able to assign a "pointer to const" to a "const pointer to non-const" inside your class, which would remove constness without a cast. This would obviously allow you to violate invariants and couldn't be allowed.
No, because copy elision (and the so-called guaranteed copy elision) can change the constness of an object "after" construction:
struct A {
bool c;
A() : c(magic_i_am_const()) {}
A(const A&)=delete; // immovable
};
const A f() {return {};}
A g() {return f();} // OK
void h() {
A x=f(); // OK
const A y=g(); // OK
}
What should x.c
and y.c
be?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With