C + + container and inheritance

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.