Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ whats the difference between setters and getters and constructors?

Tags:

c++

oop

If we use constructors do we need to use setters and getters. I am totally confused between these terms could someone please elaborate.


2 Answers

If we use constructors do we need to use setters and getters

First of all you cannot have a class without a constructor, when you do not provide any compiler will generate them for you. You should not use setters and getters unrelated if you define your own constructor or not. When you design a class you design it's interface and then add member variables to implement that behavior and those members are internal representation of the class and outside world should not be aware of them - that is what data encapsulation is for and that's why we make them private or protected. When you add members first and then blindly provide getters and/or setters - that is a wrong approach to OOD.

like image 76
Slava Avatar answered Nov 21 '25 23:11

Slava


Use constructors to create objects. Use getters to get information from an already existing object. Use setters to change an already existing object.

Any particular class may will need one or more of these things but not every class will need all of them. In particular immutable classes can't be modifed after they've been created so don't need setters.

like image 27
john Avatar answered Nov 22 '25 00:11

john



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!