Objects vs. Data Structures

As you surely know, C++ supports object-oriented programming (OOP). But objects themselves are actually very similar to data structures, introduced back in the early days of C. Most of the stuff you code can be implemented by using either one of them. What’s more, if you change your mind, they are pretty easily interchangeable. Why are then objects even introduced into the language? When and why should you prefer one over the other? Do you even need data structures? Let’s find out.
Data structures, or structs, exist to meaningfully group related data for easier reusability and maintainability. That data is exposed so it can be used without unnecessary complications. Furthermore, while data structures can contain operations, conceptually they don’t need to. Therefore, they are primarily used as simple data containers.
struct Employee() {
std::string firstName; // public
std::string lastName; // public
int salary; // public
}
Objects, on the other hand, encapsulate their data. They purposefully hide that data behind functions used to manipulate it. Consequentially, objects are primarily used to achieve data abstraction.
class Developer: Employee() {
int salary; // private
int hoursWorked; // private
public:
int getSalary() {
…
return salary;
}
}
Your choice therefore depends on the way you intend to use the data in question. Data structures make it easy to change existing behaviors but difficult to add new types. Contrary to that, objects make it easy to add new types but difficult to change existing behaviors. Try not to create hybrids, they introduce problems from both worlds.
Let’s take a look at an example class. As already stated, when using objects, your goal should be to create data abstractions. This is not achieved by only hiding the details with getters and setters.
class Employee() {
std::string firstName;
int salary;
public:
std::string getFirstName() {
return firstName;
}
int getSalary() {
return salary;
}
void setFirstName(std::string name) {
firstName = name;
}
void setSalary(int salary) {
firstName = name;
}
}
This class would be better represented by a data structure. It makes no sense hiding its members behind functions which then expose them to all users. Once again, the goal is to create abstract interfaces that manipulate the essence of data.
Keep these suggestions in mind the next time you need to create a new type and make your code more suitable for the feature you’re implementing.
Stay tuned and happy coding.

