0

I know C programming can implement OOP concept, and I saw a small code do that like bellow. However the implementation in main function confuse me:

Car c;

vehicleStart((Vehicle*) &c);

Why struct Car c can directly pass to vehicleStart parameter, although it has been type casting. I think they have different type in struct Vehicle base; Object base; so this operation confuse me.

#include <stdio.h>

typedef struct Object Object;   //!< Object type
typedef struct Vehicle Vehicle; //!< Vehicle type
typedef struct Car Car;         //!< Car type
typedef struct Truck Truck;     //!< Truck type

/*!
 * Base object class.
 */
struct Object {
    int ref;    //!< \private Reference count.
};

static Object * objRef(Object *obj);

static Object * objUnref(Object *obj);

struct Vehicle {
    Object base;    //!< \protected Base class.
};


void vehicleStart(Vehicle *obj);


void vehicleStop(Vehicle *obj);

struct Car {
    Vehicle base;    //!< \protected Base class.
};

struct Truck {
    Vehicle base;    //!< \protected Base class.
};

/* implementation */
void vehicleStart(Vehicle *obj)
{
    if (obj) printf("%x derived from %x\n", obj, obj->base);
}

int main(void)
{
    Car c;
    vehicleStart((Vehicle*) &c);
}
張皓翔
  • 341
  • 1
  • 4
  • 16
  • Due to how the structures and laid out, the `Car` structure contains a `Vehicle` structure (which in turn contains an `Object` structure). Because of this a pointer to a child-structure can be casted to a pointer to the base-structure (i.e. from `Car *` to `Vehicle *`). The opposite cast isn't necessarily possible. – Some programmer dude Sep 01 '19 at 14:28
  • On another note, when you want to print a pointer with `printf` then use the `"%p"` format specifier. The `"%x"` specifier expects a value of type `int`. Mismatching format specifier and argument leads to *undefined behavior*. – Some programmer dude Sep 01 '19 at 14:29
  • 1
    Or to be more precise the opposite cast is equally valid too, provided that the `Vechicle` is the initial member of a `car`, say. (The standard says *and vice versa*) – Antti Haapala -- Слава Україні Sep 01 '19 at 14:39

0 Answers0