c++ - Are base class objects implicitly added to derived classes? -


i have read subobjects in standard saying this:

a subobject can member subobject (9.2), base class subobject (clause 10), or array element.

i have encountered lot of situations when reading c++ subojects mentioned without having subobject(explicitly defined) in derived class.

but mean whenever class has base class, compiler implicitly adds object of base class type in derived class?

like:

class base { }; class derived : base { }; 

so subobject of base has been added in derived?

is there in standard should have read? aware of tiny quotation though.

update:

if had these classes:

class base { int anint; float afloat; }; class derived : base { //inherited member variables... }; 

so in code above, anint, afloat subobjects of base? anint , afloat subobjects of derived? , there added member derived looks base something? in end, derived has 3 subobjects: anint, afloat , base something?

well, yes. derived class contain sub-objects of each class derives from. quote c++17 (n4659 draft), [class.derived/3]:

the base-specifier-list specifies type of base class subobjects contained in object of derived class type. [ example:

struct base {   int a, b, c; }; struct derived : base {   int b; }; struct derived2 : derived {   int c; }; 

here, object of class derived2 have subobject of class derived in turn have subobject of class base.  — end example ]

the term sub-object used more because inheritance not way form aggregate types. can add members class, sub-objects well. , when form arrays, each element sub-object of array whole.


to address update question:

so in code above, anint, afloat subobjects of base?

yes. members of base , therefore sub-objects of it. memory location laid out inside memory of base object.

are anint , afloat subobjects of derived?

yes, on account of inclusion being transitive. derived contains sub-object of base.

and there added member derived looks base something?

there no named member base sub-object. there chunk of memory inside derived object has base object constructed in it.

so in end, derived has 3 subobjects: anint, afloat , base something?

yes. looks this:

+----------------------+ |+--------------------+| || int    |   float   || |+--------------------+| | base object (unnamed)| +----------------------+   derived object 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -