Multiple constructors in C

Posted by meepz on Stack Overflow See other posts from Stack Overflow or by meepz
Published on 2010-03-19T02:27:08Z Indexed on 2010/03/19 2:31 UTC
Read the original article Hit count: 422

Filed under:

Hello, I am making a string class in C as a homework and I was wondering how I can make multiple constructors with the same name given the parameter. The commented out area is what I tried to do with results from a few searches but that gives me errors. Pretty much I have some cases where I want to create my new string without any parameter then in other cases create a string with a pointer to character. Here is mystring.h

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

typedef struct mystring {
char * c;
int length;

int (*sLength)(void * s);
char (*charAt)(void * s, int i);
int (*compareTo)(void * s1, void * s2);
struct mystring * (*concat)(void * s1, void * s2);
struct mystring * (*subString)(void * s, int begin, int end);
void (*printS)(void * s);

} string_t;
typedef string_t * String;

String newString(char * c);
String newString2();
int slength(void * s);
char charat(void * S, int i);
int compareto(void * s1, void * s2);
String concat(void * s1, void * s2);
String substring(void * S, int begin, int end);
void printstring(void * s);

And here is mystring.c

#include "mystring.h"

String newString(){
}
String newString(char * input){
//String newString::newString(char * input)  {
String s;
s = (string_t *) malloc(sizeof(string_t));
s->c = (char *) malloc(sizeof(char) * 20);
int i = 0;
if (input == NULL){
    s->c[0] = '\0';
    return s;
}

while (input[i] != '\0') {
    s->c[i] = input[i];
    i++;
}
//functions
s->sLength = slength;
s->charAt = charat;
s->compareTo = compareto;
s->concat = concat;
s->subString = substring;
s->printS = printstring;
return s;

}

© Stack Overflow or respective owner

Related posts about c