Virtual inheritance in C + + (virtual inheritance)

Source: Internet
Author: User

Virtual inheritance is primarily to prevent the base class from repeating inheritance, containing multiple identical base classes, resulting in ambiguity and inheriting with virtual base class (virtual base Class), which enables the derived object to contain only one copy of the base class file.

If you do not use virtual inheritance, the derived class needs to provide a copy of your own sample version,

See also: http://blog.csdn.net/caroline_wendy/article/details/18077235

Code:

/* cppprimer.cpp * * Created on:2014.1.10 * author:spike//*eclipse CDT, gcc 4.8.1*/  #include <iostream> #include <string> class Zooanimal {public:void zooprint (void) { Std::cout << "Zoo animal!" << Std::endl;  
      
}  
}; Class Raccoon:public virtual Zooanimal {public:void raccprint (void) {std::cout << "raccoon!" << Std::endl;  
      
}  
}; Class Bear:public virtual Zooanimal {public:void bearprint (void) {std::cout << "bear!" << std::e Ndl  
      
}  
}; Class Panda:public bear, public Raccoon {public:void pandprint (void) {std::cout << "panda!" << s Td::endl;  
      
}  
};  
void Dance (bear& B) {b.bearprint ();  
} void Rummage (raccoon& R) {r.raccprint ();  
    int main (void) {Panda P;  
    P.zooprint ();  
    Dance (P);  
Rummage (P); }

Output:

Zoo animal!  
bear!  
raccoon!

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

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.