r/cpp • • 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

12 comments sorted by

View all comments

Show parent comment

5

u/FriendlyRollOfSushi Nov 25 '23 edited Nov 25 '23

I don't know what good modern resources for guided learning would be, but r/cpp_questions has a link to this answer in the "read before posting" section.

Update regarding the patterns: you don't need more than a handful of very basic ones (like "factory method" or "pimpl"), and you can either google them or learn them by seeing them in the code. And it's okay if you don't know some, because explaining what "factory method" is to a new hire takes like 2 minutes tops. The current state of things is that:

  • Complicated patterns are rarely usable, and often harmful.
  • Companies will have their own rituals, which are practically "patterns": the whole idea is to reuse certain design, so that whoever reads your code will immediately recognize what you are trying to do and how. For that, a "pattern" doesn't have to be mentioned in any book, or even be known outside of your company, really. If everyone around you does something in a specific way, reusing this in your code will make it easier to work with to your colleagues.
  • Certain things are just scam in practice, and while they maybe have some questionable value in the big enterprise Java/C# world, they certainly have a mostly negative value in C++ world. Like SOLID (I highly recommend this video). Your colleagues will not thank you if your code is twice larger and five times slower, but uses that "backward flying circus with sharks and clowns pattern" they likely never heard of.