Differences between copy (copy) and virtual copy (virtual copy) in C + +

Source: Internet
Author: User
Tags count final

In the inheritance process, you need to distinguish between copy and virtual copy (virtual copy);

When a derived class is converted to a base class, it is possible for copy (copy) to cut out the derived part of the derived object (sliced down), preserving only the base class part, so that the virtual function of the derived class cannot be used;

To avoid this situation, if the incoming is an object, you can define a virtual function clone so that the derived class inherits the virtual function and then passes in the container, overloading the method;

In addition, if the incoming is an argument, add the container using Shared_ptr<base> with make_shared<derived>, or you can do dynamic binding;

In the container, the container automatically invokes the overloaded method of the derived class to implement dynamic binding;

Note: The reference qualifier (reference qualifier) GCC 4.8.1 can be supported;

Code:

* * * CppPrimer.cpp * * Created on:2013.11.12 * author:caroline//*eclipse cdt*/#includ E <iostream> #include <string> #include <vector> #include <set> #include <utilit  
      
y> #include <memory> #include <cstddef> using namespace std;  
      
Class Quote;  
    Class Quote {public:quote () = default; Quote (const std::string& book, double sales_price): Bookno (book), Price (Sales_price) {} void Add_i  
    TEM (const quote& Sale);  
    std::string ISBN () const {return bookno}  Virtual Double Net_price (std::size_t N) const {return n = Price;}//virtual function Virtual quote* clone () const & {return  
    New Quote (*this);}  
    Virtual quote* Clone () && {return new Quote (Std::move (*this)); Virtual ~quote () = default;  
Dynamic binding destructor private:std::string Bookno;  
Protected://protected type Double price = 0.0;  
      
}; Class Disc_qUote:public Quote {//abstract base class public:disc_quote () = default; Disc_quote (const std::string&, double, std::size_t qty, double Disc): Quote (book, price), quant ity (qty), Discount (disc) {} double Net_price (std::size_t) const = 0;  
        Pure virtual function protected:std::size_t quantity = 0;  
Double discount = 0.0;  
      
};  
    Class Bulk_quote Final:public disc_quote {//final qualifier, cannot be inherited public:bulk_quote () = default;  Bulk_quote (const std::string& book, double p, std::size_t qty, double disc): Disc_quote (Book, p, qty, disc)  
    {}///Using the constructor of the base class double Net_price (std::size_t cnt) const override;  
    Virtual bulk_quote* Clone () const & {return new bulk_quote (*this);}  
Virtual bulk_quote* Clone () && {return new Bulk_quote (Std::move (*this));  
      
}; Double Bulk_quote::net_price (std::size_t cnt) const {if (CNT >= quantity) return CNT * (1-discount) *  
    Price
Else        return CNT * PRICE; Double Print_total (std::ostream &os, const quote& Item, std::size_t N) {double ret = item.net_  
    Price (n); Os << "ISBN:" << item.isbn () << "# Sold:" << n << "total due:" << ret << St  
    D::endl;  
return ret; Class Basket {public:void Add_item (const std::shared_ptr<quote> &sale) {Items.insert (sale ); } void Add_item (const quote& sale) {//items.insert std::shared_ptr<quote> (new Quote (sale )));  
    Items.insert (Std::shared_ptr<quote> (Sale.clone ()) is not dynamically bound; } void Add_item (quote&& sale) {//items.insert std::shared_ptr<quote> (std:: Move (sale)));  
    Items.insert is not dynamically bound (std::shared_ptr<quote> (Std::move (Sale). Clone ()));  
Double total_reciept (std::ostream&) const; private:static bool Compare (const STD::SHARED_PTR<Quote> &AMP;LHS, const std::shared_ptr<quote> &AMP;RHS) {return LHS-&GT;ISBN () < rhs- &GT;ISBN ();  
    };  
Std::multiset<std::shared_ptr<quote&gt, Decltype (Compare) *> items{compare};  
      
};  
    Double basket::total_reciept (std::ostream &os) const {Double sum = 0.0;  
            for (Auto iter = Items.cbegin (); Iter!= items.cend (); iter = Items.upper_bound (*iter)) {//skip book with same name, calculate count sum + + print_total (OS, **iter, Items.Count (*iter)) directly;//*it is shared_ptr;  
    **it is the object} OS << "Total Sale:" << sum << std::endl;  
return sum;  
    int main (void) {basket bsk;  
    /*bsk.add_item (std::make_shared<quote> ("Cppprimer", 45));  
    Bsk.add_item (std::make_shared<bulk_quote> ("Effectivecpp", 50, 2, 0.15));  
    Bsk.add_item (std::make_shared<bulk_quote> ("Effectivecpp", 50, 2, 0.15)); Bsk.add_item (std::make_shared<bulk_quote> ("EffectivecPP ", 2, 0.15)); */Bsk.add_item (Quote (" Cppprimer ", 45));  
    Bsk.add_item (Bulk_quote ("Effectivecpp", 50, 2, 0.15));  
    Bsk.add_item (Bulk_quote ("Effectivecpp", 50, 2, 0.15));  
      
    Bsk.add_item (Bulk_quote ("Effectivecpp", 50, 2, 0.15));  
      
    Bsk.total_reciept (std::cout);  
      
return 0; }

Output:

Isbn:cppprimer # sold:1 Total due:45  
isbn:effectivecpp # sold:3 Total due:127.5 Total  
sale:172.5

Author: csdn Blog spike_king

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

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.