Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

How can I call an object from a main class?

Name: Anonymous 2011-04-02 8:27

How do I call an object from the main class in java and c?

Name: Anonymous 2011-04-02 12:34

ENTERPRISE QUALITY OOP C


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Shape;

typedef char* (*TellShape)(Shape* shape, char* buf, size_t bufsz);

typedef struct Shape {
    TellShape tellshape;
    void* data;
};

typedef struct squaredata {
    int width, height;
};

void SquareConstructor(Shape* shape, void* params)
{
    shape->data = malloc(sizeof(squaredata));
    squaredata* p = (squaredata*)shape->data;
    p->height = ((int*)params)[1];
    p->width = ((int*)params)[0];
}

char* SquareTell(Shape* shape, char* buf, size_t bufsz)
{
    squaredata* p = (squaredata*)shape->data;
    char buf2[12];
    char ret[64];
    itoa(p->width, buf2, 10);
    ret[0] = 0;
    strcat(ret, "Square - Width: ");
    strcat(ret, buf2);
    strcat(ret, ", Height: ");
    itoa(p->height, buf2, 10);
    strcat(ret, buf2);
    if(strlen(ret) >= bufsz)
        return 0;
    strcpy(buf, ret);
    return buf;
}

void SquareDeconstructor(Shape* shape)
{
    free(shape->data);
}

typedef struct circledata {
    int radius;
};

void CircleConstructor(Shape* shape, void* params)
{
    shape->data = malloc(sizeof(circledata));
    circledata* p = (circledata*)shape->data;
    p->radius = *((int*)params);
}

char* CircleTell(Shape* shape, char* buf, size_t bufsz)
{
    circledata* p = (circledata*)shape->data;
    char buf2[12];
    char ret[64];
    itoa(p->radius, buf2, 10);
    ret[0] = 0;
    strcat(ret, "Circle - Radius: ");
    strcat(ret, buf2);
    if(strlen(ret) >= bufsz)
        return 0;
    strcpy(buf, ret);
    return buf;
}

void CircleDeconstructor(Shape* shape)
{
    free(shape->data);
}

Shape* ConstructSquare(int width, int height)
{
    int params[2];
    params[0] = width;
    params[1] = height;
    Shape* ret = (Shape*)malloc(sizeof(Shape));
    ret->tellshape = SquareTell;
    SquareConstructor(ret, params);
    return ret;
}

void DestroySquare(Shape* square)
{
    SquareDeconstructor(square);
    free(square);
}

Shape* ConstructCircle(int radius)
{
    Shape* ret = (Shape*)malloc(sizeof(Shape));
    ret->tellshape = CircleTell;
    CircleConstructor(ret, &radius);
    return ret;
}

void DestroyCircle(Shape* circle)
{
    CircleDeconstructor(circle);
    free(circle);
}

int main(int argc, char* argv[])
{
    Shape* sq = ConstructSquare(5, 7);
    Shape* ci = ConstructCircle(12);
    char buf[128];
    printf("%s\n", sq->tellshape(sq, buf, 128));
    printf("%s\n", ci->tellshape(ci, buf, 128));
    getchar();
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List