Conteúdo do Curso
C++ OOP
C++ OOP
Why use Object-Oriented Programming?
Imagine you were given a task to develop a software application to manage student data. It might seem straightforward at first. You might begin by using simple variables to store a student’s name and GPA.
main
int main() { std::string student_name = "Bob"; float grade_point_average = 3.3; }
This approach works fine for managing a single student, but things get more complex with multiple students. A naive solution might use separate variables for each one, but this quickly becomes unmanageable. Using arrays is a better option to reduce repetition and improve organization.
main
int main() { std::string names[2] { "Bob", "Ann" }; float avarage_grades[2] { 3.3, 3.7 }; }
This works for now. But what if you need to store more details, such as phone numbers, enrollment dates, or course lists? As the data grows, managing multiple separate arrays becomes cumbersome and error-prone.
main
int main() { std::string names[2] { "Bob", "Ann" }; float average_grades[2] { 3.3f, 3.7f }; std::string emails[2] { "bob@example.com", "ann@example.com" }; }
To manage this data, you might create functions that take these values as arguments to perform actions like printing student info, updating the GPA, or changing the email address. But with multiple students and fields, you end up repeating the same arguments across many functions, making the code error-prone and hard to maintain.
functions
void get_student_info(int id, std::string names[], float gpa[], std::string emails[]); void set_student_info(int id, std::string names[], float gpa[], std::string emails[]); void set_student_name(int id, std::string names[], float gpa[], std::string emails[]); void set_student_gpa(int id, std::string names[], float gpa[], std::string emails[]); void set_student_email(int id, std::string names[], float gpa[], std::string emails[]);
Even simple tasks require passing the same set of arrays repeatedly. As you add more fields, the code becomes increasingly complex and repetitive.
Object-Oriented Programming (OOP) solves this by allowing you to group related data and behavior into a single container called a class. This not only simplifies your code, but also improves encapsulation by controlling access to internal details through clear, well-defined interfaces.
Obrigado pelo seu feedback!