2

I have a doubt regarding the concept of encapsulation.

Isn't C language also does the encapsulation by 'struct' data type?

the data variables and the functions present in the struct can only be called by the struct variable. and no other variable in the system. Isn't it data hiding?

I am trying to relate this concept to understand C++ encapsulation.

Vimal
  • 1,266
  • 1
  • 9
  • 16
Vinay
  • 107
  • 1
  • 3
  • 15
  • 1
    Your question is a little unclear. Can you please improve it ? – cnicutar Dec 23 '11 at 20:20
  • 1
    In C, you can't have "functions present in the struct". I suspect your compiler is mis-configured and is compiling C++. – pmg Dec 23 '11 at 20:21
  • I have not programmed in C in years, but as far as I remember you can reference the struct variables from any object that has a pointer to the struct. – Sergio Dec 23 '11 at 20:24
  • @pmg - yes I checked with the compiler. only C++ allows functions. Thanks. Sergio - I am not able to understand the concept. If possible , please explain it with code example. thank you. – Vinay Dec 23 '11 at 21:01
  • in C you can have function pointers in your struct, which is fairly close to 'having functions' – paleozogt Dec 23 '11 at 21:07

1 Answers1

2

There really only exists "partial hiding" of structs in C. You can look at this post for a more detailed explanation:

Is there any workaround for making a structure member somehow 'private' in C?

However, encapsulation in C++ is relatively similar. You cannot completely hide all data members from the client code (even if they are in the private section). It is seemingly a "violation" of encapsulation, but this is the nature of the language.

Community
  • 1
  • 1
RageD
  • 6,693
  • 4
  • 30
  • 37
  • thanks RageD. Yes, I had checked that thread previously. I guess did not know that C does not support functions in struct only C++ does. So can we say in broad sense C++ struct and class offer similar encapsulation mechanism? as both offer data bundling and hiding.(though there are differences like encapsulation through inheritance) – Vinay Dec 23 '11 at 20:56
  • Yes, they offer similar mechanisms. Notice that the main difference for a `struct` vs. `class` in C++ is that the default members are `public` for a `struct` and `private` for a `class` – RageD Dec 24 '11 at 06:13