Two override examples in C ++

Source: Internet
Author: User
/*
 * main.cc
 *
 *  Created on: 2008-8-5
 *      Author: Administrator
 */
#include <iostream>
 
class Base
{
public:
    virtual Base *clone(){ std::cout << "Base::clone() \n"; return new Base;}
};
 
class Derived : public Base
{
public:
    Derived *clone(){ std::cout << "Derived::clone() \n"; return new Derived;}
};
 
int main(int arg, char **args)
{
    Derived *pd = new Derived;
    pd->clone();
 
    Base *pb = pd;
    pb->clone();
 
    return 0;
}

Result:

Derived: Clone ()
Derived: Clone ()

We can see that although the return types are not exactly the same, the return value in the parent class is a pointer or reference. When the subclass override, we can return the derivation of this pointer (or reference). In this case, override succeeded.

Let's look at the following example:

 
#include <iostream>
 
class Base
{
public:
    virtual Base *clone(){ std::cout << "Base::clone() \n"; return new Base;}
    virtual void copy(Base&){ std::cout << "Base::copy() \n"; }
};
 
class Derived : public Base
{
public:
    Derived *clone(){ std::cout << "Derived::clone() \n"; return new Derived;}
    void copy(Derived&) { std::cout << "Derived::copy() \n"; }
};
 
int main(int arg, char **args)
{
    Derived d;
    Base b;
 
    Derived *pd = new Derived;
    pd->copy(d);
 
    Base *pb = pd;
    pb->copy(b);
 
    return 0;
}

Result:

Derived: Copy ()
Base: Copy ()

In this case, override does not occur, and hide does.

Set

void copy(Derived&) { std::cout << "Derived::copy() \n"; }

Changed:

void copy(Base&) { std::cout << "Derived::copy() \n"; }

Override is successful!

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.