Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...