using C as a OO langauge

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JonLT
    New Member
    • Jul 2007
    • 41

    #1

    using C as a OO langauge

    Hi
    I've been using C++ quite a lot now, but i have recently moved over to C, and because of my experience with C++ i tend to use C in the same way as I used C++.

    e.g:
    [code=c]
    typedef struct SMyStruct
    {
    int A,B,C;
    } MyStruct;

    int myStruct_set_va lues(MyStruct* s, int a, int b, int c)
    {
    s->A = a;
    s->B = b;
    s->C = c;
    }
    [/code]

    I feel that I'm using C the wrong way, as I'm really creating objects and member functions.
    Is the above code following conventions?
    If not, how would you do it?
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by JonLT
    Hi
    I've been using C++ quite a lot now, but i have recently moved over to C, and because of my experience with C++ i tend to use C in the same way as I used C++.

    e.g:
    [code=c]
    typedef struct SMyStruct
    {
    int A,B,C;
    } MyStruct;

    int myStruct_set_va lues(MyStruct* s, int a, int b, int c)
    {
    s->A = a;
    s->B = b;
    s->C = c;
    }
    [/code]

    I feel that I'm using C the wrong way, as I'm really creating objects and member functions.
    Is the above code following conventions?
    If not, how would you do it?

    I dont feel what u are doing is wrong.
    Its better to have functions in C which does a specific job.
    The only difference is that it may not be part of the structure directly.

    Raghuram

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      This is slightly unusual and I have only really seen this done like this in C where the code is hiding the type from the calling code

      e.g:
      [code=c]
      typedef struct SMyStruct
      {
      int A,B,C;
      } MyStruct;

      int myStruct_set_va lues(void *vs, int a, int b, int c)
      {
      MyStruct *s = vs;

      s->A = a;
      s->B = b;
      s->C = c;
      }
      [/code]
      Somewhere they would be a function that creates a MyStruct and returns a pointer to it cast to void *

      This is the basic set-up for an Abstracted Data Type (ADT). In a type like this the calling code has no direct access to the data which is enforced by keeping the data structures private to the ADT internal code. The calling code is returned a unique identifier to it's data (this could be a void * as above or any identifying int that allows the ADT to correctly locate the data in question). The calling code effectively requests data and then calls function to manipulate the data all in the ADT but never has direct access to the data giving the designer of the ADT much better control of it (unless some numpty circumvents the whole thing by hacking direct access to the ADT's data).

      Comment

      Working...