Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Just started learning about classes in C++ and I\'m have trouble understanding w

ID: 655571 • Letter: J

Question

Just started learning about classes in C++ and I'm have trouble understanding why object orientated programming (OOP) is useful. I understand the syntax, how to use them etc.

But I'm still confused as to why OOP is advantageous. Here are some specifics I'm having trouble with:

Private variables. What is the use? Many sources tell me its to prevent outsiders from changing internal variables of the object, to protect the "insides". That doesn't make sense to me because wouldn't someone who wanted to change the variable just call the setter (mutator) functions and change it? Anyone can open the source file and call the setter and change the value of the variable. How is that "protection"? It's also mentioned that it makes debugging easier because instead of looking for every instance of the variable "x", you know "x" is only accessible through the class. So instead of ctrl+F "x" you just ctrl+F "memberFunction"?? How does that make debugging easier?

I read somewhere that using getters and setters is bad. Although sometimes unavoidable, its generally bad. I read "Don't ask for the information you need to do the work; ask the object that has the information to do the work for you." Can someone explain why this is important?

The big picture. I don't understand why implementing objects is more efficient than just if-statements and function calls....when there are functions in objects too. Objects don't seem to save tons of time in terms of coding. What am I missing?

Explanation / Answer

Perhaps an example can help explaining the benefits of object oriented programming.

Consider a linked list, it consist of node structures containing some data and pointing to other nodes:

struct Node {
Node* next;
int data;
}
Assume a list of these (I named them for convenience):

Node c{null, 4};
Node b{&c, 73};
Node a{&b, 42};
Node* list = &a;
You can use this list as follows:

std::cout << list->data; // prints 42
std::cout << list->next->data; // prints 4
All is fine here, but imagine somewhere in your program the following happens:

Node d{&a, 17};
list->next->next = &d;
Now the list is messed up, it is: [a, b, d, a, b, d,