tags:

views:

1000

answers:

7

Can i inherit structure in C?if yes how?

+1  A: 

No you cannot. C does not support the concept of inheritance.

JaredPar
doesn't support but doesn't get in the way either.
Javier
+1  A: 

C is not an object-oriented language and hence has no inheritance.

txwikinger
+1  A: 

You can simulate it, but you can't really inherit.

luiscubal
what's _reality_? C++ is just a very simple runtime library for dispatching and a lot of compiler syntax to call it when needed. the original C++ compilers produced C code, after all. (and very readable C in fact)
Javier
Meanwhile, other users have shown HOW to do this.
luiscubal
+12  A: 

C has no explicit concept of inheritance, unlike C++. However, you can reuse a structure in another structure:

typedef struct {
    char name[NAMESIZE];
    char sex;
} Person;

typedef struct {
    Person person;
    char job[JOBSIZE];
} Employee;

typedef struct {
    Person person;
    char booktitle[TITLESIZE];
} LiteraryCharacter;
anon
As far as I know, you can have a struct/class member inside another in C++ as well.
Tyler Millican
Of course you can.
anon
C says that no padding appears before the first member of a struct. So you can in fact (and are allowed) cast LiteraryCharacter* to Person*, and treat it as a person. +1
Johannes Schaub - litb
A: 

No, you cant. imo the best approach to OOP in C is using ADT.

Macarse
+13  A: 

The closest you can get is the fairly common idiom:

typedef struct
{
    // base members

} Base;

typedef struct
{
    Base base;

    // derived members

} Derived;

As Derived starts with a copy of Base, you can do this:

Base *b = (Base *)d;

Where d is an instance of Derived. So they are kind of polymorphic. But having virtual methods is another challenge - to do that, you'd need to have the equivalent of a vtable pointer in Base, containing function pointers to functions that accept Base as their first argument (which you could name this).

By which point, you may as well use C++!

Daniel Earwicker
Well, that's assuming a C++ compiler is available for your platform!
Anthony Cuozzo
If a C compiler is available, then so is a C++ compiler - just use one that produces C as its output.
Daniel Earwicker
+2  A: 

You can do the above mentioned

typedef struct
{
    // base members

} Base;

typedef struct
{
    Base base;

    // derived members

} Derived;

But if you want to avoid pointer casting, you can using pointers to a union of Base and Derived.

MighMoS