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
768 views
in Technique[技术] by (71.8m points)

oop - C++ multiple inheritance order

I'm trying to understand the affect of inheritance order in C++.. I looked online, but I couldn't find a clear and sufficient answer...

So, for the sake of the question, assume there are 2 classes: class B and class C.

Now, define:

class A1 : public B, public C{ ... };
class A2 : public C, public B{ ... };

What is the difference between A1 and A2?

Thanks a lot!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The C++11 Standard says (§10.1) [class.mi]:

The order of derivation is not significant except as specified by the semantics of initialization by constructor (12.6.2), cleanup (12.4), and storage layout (9.2, 11.1).

The three referenced paragraphs reveal that

  • Constructors are called in the order you write them down (first base class in the list is constructed first) (§12.6.2.10). Different rules apply to virtual base classes which are always constructed from the most-derived class before any direct base classes.
  • Destructors are called in the inverse order of construction (first base class in the list is destructed last)
  • Storage layout is unspecified. You must not make any assumptions about the class layout in memory. The only exception are so called standard-layout classes (§9), which is basically a C-style struct. But since those are not allowed to have more than one class with non-static members in the class hierarchy, the question does not really apply here.

Note that the memory layout can be important. For example, if an external library makes naive C-style casts that assume that the part of the object it's interested in is at the beginning, it can lead to run time errors that are hard to debug.


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

...