C++/about oops
Expert: Eddie - 3/18/2005
Questionwhat is the definition of encapsulation?
if i declare a data member as public whether it fulfill the criteria of encapsulation in a class
AnswerHello, rajesh kushwaha. Thank you for the question.
In regards to programming, data encapsulation refers to the ability to hide data in a program by means of indirect accessors and mutators to it. Declaring data members public would not be data encapsulation by many standards. That also depends on your criteria you have to follow. Here is a quick example of an accessor and mutator to an encapsulated data member:
class Test
{
private:
int x;
public:
Test();
~Test();
int GetX() {return x;}
int SetX(const int _x) {x = _x;}
}
int main()
{
Test t;
t.SetX(5);
std::cout << t.GetX() << '\n';
return 0;
}
That shows how to get and set an object's encapsulated data member, in case you were confused. Of course, there is always the argument that if you're going to be Getting and Setting data members all the time, why not make them public? Most people consider this bad OOP. The overhead of compiler implicit function calls is virtually nonexistent because the compiler inlines those function calls at run time.
I hope this information was helpful.
- Eddie