'How to respect encapsulation principles in c++ without making the code unefficient?
i am a noobie in c++ programming and i'm developing a project in c++. I am new to the all the OOP principles like encapsulation and inheritance, and due to this i have a doubt on how to properly design the code in particular structures. Suppose for example i have to define a structure like that:
class c1;
class c2;
class MyCl{
public:
MyCl();
// many access methods...
//...
//...
private:
std::string _title;
int _version;
std::vector<c1> _vec;
// other private members
}
class c1{
public:
c1();
// many access methods
private:
std::vector<c2> _vec;
// other private members
}
class c2{
public:
c2();
//many access methods
private:
std::vector<std::string> _vec_str;
// other private members
}
Now suppose we have an object of MyCl and we want to modify a single string amongst all in the vector _vec_str, placed in the least exposed part of the structure(c2). So in that case what is the best option to modify that string respecting the encapsulation principle? Returning const& seems unefficient, as in order to modify a single string we have to copy all the structure two times (one for the getters, and one for the setters) and for each subclass. On the other hand, returning & or pointers is more efficient as it allows a direct access to all the structure, but it doesn't respect encapsulation principles.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
