Problems with the child class of C + + and the parent class cast

Source: Internet
Author: User

Recently, in a class in a project, if you encounter a virtual virtual function that wants to cast a subclass into a parent class, then call its parent version.

it will appear . GCC compilation error Hint: Error:ld returned 1 exit status

GCC hint reason: In the link process, found unable to find the reference symbol, the reference symbol is the copy constructor of this parent class.

From this, I infer that the reason for the problem is that the copy constructor of the parent class is called by default in the process of converting a subclass into a parent class. Disallow_copy_and_assign (XXX) is used for most classes in the project; This macro declaration is not implemented, which is equivalent to banning the copy constructor. The macro is defined as follows:

#define DISALLOW_COPY_AND_ASSIGN (ClassName) ClassName (const classname&); void operator= (const classname&)

The workaround is to convert its type, but not to use the copy constructor (copy constructor), as follows:

With parrent& instead of static_cast<parrent> (*this), using references instead of classes, you can avoid copying new objects and naturally avoid calling their copy constructors.

Reference:

1. Http://stackoverflow.com/questions/9084835/why-does-static-castthis-to-a-base-class-create-a-temporary-copy

Problems with the child class of C + + and the parent class cast

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.