Created
March 25, 2019 15:03
-
-
Save kateolenya/ed6a1fade19c3a6ca55e1b852493f163 to your computer and use it in GitHub Desktop.
Inheritance in C, short version of struct as pure superset of another struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.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); | |
} | |
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); | |
} | |
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