Results 1 to 5 of 5

Thread: C "classes"

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    thinBasic MVPs danbaron's Avatar
    Join Date
    Jan 2010
    Location
    California
    Posts
    1,378
    Rep Power
    152

    C "classes"

    Here is my (probably primitive) way of imitating classes and object creation/destruction in C.



    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
    
    //-------------------------------------------------------------------------------------------------------------
    
    // Use a struct to function as the data part of the class.
    
    struct Astruct
    {
    int N[10];
    bool B;
    };
    
    // Make a function to return a new instance of the struct.
    
    struct Astruct* newAstruct(void)
    {
    return malloc(sizeof(struct Astruct));
    }
    
    // Make functions which take the struct as a parameter.
    
    void AstructSetN(struct Astruct* as, int index, int value)
    {
    as->N[index] = value;
    }
    
    int AstructGetN(struct Astruct* as, int index)
    {
    return as->N[index];
    }
    
    void AstructSetB(struct Astruct* as, bool value)
    {
    as->B = value;
    }
    
    bool AstructGetB(struct Astruct* as)
    {
    return as->B;
    }
    
    //-------------------------------------------------------------------------------------------------------------
    
    int main(int argc, char *argv[])
    {
    struct Astruct* A;
    int Nval;
    bool Bval;
    char c;
    
    A = newAstruct();
    
    AstructSetN(A, 4, 6);
    AstructSetB(A, true);
    Nval = AstructGetN(A, 4);
    Bval = AstructGetB(A);
    
    printf("Nval = %u\n", Nval);
    printf("Bval = %u\n\n", Bval);
    
    free(A);
    
    struct Astruct* C;
    C = newAstruct();
    
    AstructSetN(C, 7, 3);
    AstructSetB(C, false);
    Nval = AstructGetN(C, 7);
    Bval = AstructGetB(C);
    
    printf("Nval = %u\n", Nval);
    printf("Bval = %u\n\n", Bval);
    
    c = getchar();
    
    return 0;
    }
    
    Last edited by danbaron; 29-07-2011 at 00:23.
    "You can't cheat an honest man. Never give a sucker an even break, or smarten up a chump." - W.C.Fields

Members who have read this thread: 0

There are no members to list at the moment.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •