Alex Rivera | Logout

Why are private members/methods defined in the interface?

Asked 2011-09-08T06:35:45.967
21

I've always been confused by the fact that most OOP languages (or rather, C++) make you define private methods/members in the interface (by interface I mean the class declaration - seems like I was confused). Isn't this showing the implementation details of the class and going against the idea of encapsulation?

Is there a good reason for this that I've been missing?

Edit
Report

1 Answer

2

There are two senses, in which the word interface is used in C++: an OOP interface and a type declaration.

An OOP interface is used for encapsulation and polymorphism. In C++, it is usually implemented with pure abstract classes. The PIMPL idiom is also used for encapsulation. In either case, the consumer is shown only the type's public members and accesses the private implementation through an indirection layer. Java and C# support explicit interfaces and both restrict their members to public access.

Type declarations are required in C++ due to its linking model. A type's declaration is not its interface in the OOP sense, but because a type's declaration has to be included before use, decoupling the implementation becomes more desirable. In order to achieve this, we use OOP interfaces, as described above. There would be no need to hide private implementation details from a type's declaration, if only C++ supported modules. Module support was proposed for C++11, but due to time constraints set to be included in a future TR.

answered 2011-09-08T06:40:38.130

Your Answer