C++ OOP | Sololearn: Learn to code for FREE!



What is a constructor for? What are getters and setters for? I can set parameters for attributes without them


11 Answers

New Answer


Constructors give you an organized, standardized and slim way to initialize objects. Getters and setters protect attributes by only allowing controlled methods to check and change them. Sure anyone can do without them. Only with more work and less results.


the constructor is a method that is called when you create an object of the class setters are methods that take the value you are trying to set to a variable in the object, like so: class x: def setUwu(self, value): self.uwu = value and getters are the same but for getting the value those kind of methods are used usually in old languages and have kind of a security porpoise hope it helps


Constructor is a method which is used to create objects. Getters and setters are also methods . Getters are used to get an object's attributes and setters to edit object's attributes. Yes, you can set parameters without using them, its possible but not recommended.


By using a constructor you can initialize object's attributes in the creation time by passing parameters values through the constructor as constructor's arguments.


u can also, as Emerson Prado said instantiate some variables in the constructor in languages where you can't write variables out of the methods


Emerson Prado Why with more work? And why it is recommended to create a constructor at the beginning of the class, even if empty?


Sry, i'm use translate, because have only study English skills


Emerson Prado OK, thanks for answer. May I contact you next time?


_ᙢǾሊỢȡΘŬ_ Always prefer using the forum. This way, the answers stay available to everyone.


Ренат Гилязов No. Constructors are not needed to display anything, nor test a condition. They are intended to set initial state of objects. With or without outputs and decisions.


_ᙢǾሊỢȡΘŬ_ Without a constructor, you have to populate attributes manually. Without getters and setters, you have to expose the attributes, then implement whatever validation and processing at each attribution. Just think of the additional work and risk. And the messy maintenance. We better have the constructor at the top just so it's easy to find.