user10655470
user10655470

Reputation:

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

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

Upvotes: 2

Views: 172

Answers (3)

Tim Randall
Tim Randall

Reputation: 4145

The two things are very different.

A constructor is a function that is called by the system whenever an object is created. If you don't define one yourself, the compiler will provide a default one. Whatever happens, a constructor will be called exactly once for each object you create. Its purpose is usually to set up valid values for all members of the class.

By contrast, getters and setters are just regular functions — methods whose purpose is to provide access to individual members of a class (read and write acces, respectively). There is no requirement to provide one, and they are not automatically generated; conversely, if one is provided, it may be called as often as you like.

Hopefully it's clear how a constructor differs from set/getters.

Upvotes: 1

Slava
Slava

Reputation: 44268

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.

Upvotes: 7

john
john

Reputation: 87957

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.

Upvotes: 1

Related Questions