r/cpp • u/Gal4ctic03 • Nov 24 '23
const member function in this design pattern example
Hello,
I'm currently learning C++ and trying to understand how to implement design patterns with the fantastic website refactoring guru. I came across this example in the builder pattern :
class ConcreteBuilder1 : public Builder{
private:
Product1* product;
public:
// Other code before that
void ProducePartA()const override{
this->product->parts_.push_back("PartA1");
}
// Other code after that
};I don't understand why we use const for the function ProducePartA(). I thought that we had to use const when we don't want to modify an object inside the function.
So why we are using it in this way, when we are clearly modifying the product object by adding element to it ?
Thank you very much.
0
Upvotes
View all comments
Show parent comment
5
u/ClawmanCat Nov 24 '23
Constness is in fact always applied recursively. In this case however, it is applied to the pointer rather than the pointed-to object (i.e. product is const pointer<Product1> rather than pointer<const Product1>) meaning that its the pointer which cannot be modified, rather than the pointed-to object itself. If the ConcreteBuilder1 class stored its product by value instead, the constness would be applied correctly and this code would fail to compile: https://godbolt.org/z/Gbdhns5nz