Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in C

Tags:

c

inheritance

I am playing with implementing inheritance in C. I wrote the following two variations of it. Method 1 crashes while running the program, but Method 2 works fine. What am I doing wrong in Method 1?

Method 1:

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

typedef struct base_class
{
    int a;
}Base;

typedef struct derived_class
{
    int b;
    Base *base_ptr;
}Derived;

int main(void){
    Derived *der_ptr;
    der_ptr = (Derived *)malloc(sizeof(Derived));
    der_ptr->b = 5;
    der_ptr->base_ptr->a=10;

    printf("%d %d",der_ptr->b,der_ptr->base_ptr->a);
}

Method 2:

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

typedef struct base_class
{
    int a;
}Base;

typedef struct derived_class
{
    int b;
    Base base_ptr;
}Derived;

int main(void){
    Derived *der_ptr;
    der_ptr = (Derived *)malloc(sizeof(Derived));
    der_ptr->b = 5;
    der_ptr->base_ptr.a=10;

    printf("%d %d",der_ptr->b,der_ptr->base_ptr.a);
}
like image 324
user2761431 Avatar asked Dec 25 '22 00:12

user2761431


1 Answers

Method 1 crashes because of this line of code:

der_ptr->base_ptr->a=10;

Ask yourself: What is the value of der_ptr->base_ptr?

like image 131
wallyk Avatar answered Dec 28 '22 07:12

wallyk