+ 4
C++ OOP
What is a constructor for? What are getters and setters for? I can set parameters for attributes without them
11 Answers
+ 3
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.
+ 2
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
+ 1
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.
+ 1
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.
+ 1
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
0
Emerson Prado Why with more work? And why it is recommended to create a constructor at the beginning of the class, even if empty?
0
Sry, i'm use translate, because have only study English skills
0
Emerson Prado OK, thanks for answer. May I contact you next time?
0
_į¢Ē¾įį»¢Č”ĪŬ_ Always prefer using the forum. This way, the answers stay available to everyone.
0
Š ŠµŠ½Š°Ń ŠŠøŠ»ŃŠ·Š¾Š² 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.
- 2
_į¢Ē¾įį»¢Č”ĪŬ_
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.