Skip to content

Instantly share code, notes, and snippets.

@kateolenya kateolenya/base.c
Created Mar 25, 2019

Embed
What would you like to do?
Inheritance in C, struct as pure superset of another struct
#include "base.h"
#include <stdio.h>
struct Device {
int serial_number;
int sizeof_memory;
};
void print_values( struct Device * some_device ) {
printf("Serial number: %d, ", some_device->serial_number);
printf("memory size = %d\n", some_device->sizeof_memory);
}
#ifndef BASE_H
#define BASE_H
struct Device;
void print_values( struct Device * some_device );
#endif /* BASE_H */
#include "derived.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Computer {
int serial_number;
int sizeof_memory;
char nameof_os[10];
};
struct Computer * create_computer() {
struct Computer * some_computer;
some_computer = malloc(sizeof(struct Computer));
some_computer->serial_number = 12345678;
some_computer->sizeof_memory = 87654321;
strcpy(some_computer->nameof_os , "Windows 95");
return( some_computer );
}
void print_os( struct Computer * some_computer ) {
printf("OS is: %s\n", some_computer->nameof_os);
}
void delete_computer( struct Computer * some_computer ) {
free(some_computer);
}
#ifndef DERIVED_H
#define DERIVED_H
struct Computer;
struct Computer * create_computer();
void print_os( struct Computer * some_computer );
void delete_computer( struct Computer * some_computer );
#endif /* DERIVED_H */
#include "base.h"
#include "derived.h"
int main() {
struct Computer * My_computer;
My_computer = create_computer();
print_os( My_computer );
// note typecasting here
print_values(( struct Device * ) My_computer );
delete_computer( My_computer );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.