Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
993 views
in Technique[技术] by (71.8m points)

oop - Derived classes in C - What is your favorite method?

In my experience in object oriented C programming I have seen two ways to implement derived classes.


First Method, have a definition of the parent class as a .h file. Then each class that derives from this class will have do:

File parent_class.h:

int member1;
int member2;

File testing.c:

struct parent_class {
    #include "parent_class.h" // must be first in the struct
}

struct my_derived_class {
    #include "parent_class.h" // must be first in the struct
    int member3;
    int member4;
}

Second Method, would do:

File testing.c:

struct parent_class {
    int member3;
    int member4;
}

struct my_derived_class {
    struct parent_class; // must be first in the struct
    int member3;
    int member4;
}

What is your favorite method of doing derived classes in C ( doesn't have to be what I have done )? and why?

Which method would you prefer, first or second method ( or your own )?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first method is hideous and it hides important information. I'd never use it or allow it being used. Even using a macro would be better:

#define BODY int member1; 
             int member2; 

struct base_class
{
   BODY
};

But method 2 is much better, for reasons others have pointed out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...