If the container type is defined as a base class type, the derived class can be loaded into the container, but the derived class's own public member cannot be accessed through the container, and the derived class will be cut off, preserving only the base class portion of the derived class;
If the container is defined as a derived class type, then the base class type cannot be loaded into the container, and there is no standard conversion from the base class type to the derived class type . Although you can explicitly use forced type conversions to convert a base class into a derived class and put it into a container, they will be uninitialized if you use the derived class members of those elements.
1 classBase2 {3 Public:4Base (inti =0): Val (i) {}5 intbasepub;6 Private:7 intVal;8 };9 Ten classDerived: PublicBase One { A Public: -Derived (inti =0,intj =1): Base (i), Val (j) {} - intderivedpub; the Private: - intVal; - - }; + - + A intMain () at { - Base B; - Derived D; - -Vector<base>BS; - Bs.push_back (b); inBs.push_back (d);//cut, retaining only the base class member part -cout<<bs[1].derivedpub<<Endl; to //error, only members of the base class type can be accessed through the container + - theVector<derived>ds; * Ds.push_back (d); $ Ds.push_back (b);Panax Notoginseng //error, a container of a derived class type cannot load a base class member - return 0; the}
C + + container and inheritance