Pointer to parent class cannot point to child class object

Source: Internet
Author: User

The pointer to the parent class points to the object of the subclass, which is called polymorphic in C + +.

Of course, polymorphism can also have a deeper explanation.

But why do the pointers to the parent class sometimes point to objects that are not subclasses?

There are two files in the following code:

B.hclass b:public a{};//main.cpp Class A; Class B;  void Fun (b* b) {A * A = B; There's a mistake here}

The reason is this, and sometimes we want to improve the speed of compiling,

Will do some pre-declaration, such as Class A tells compiler A to exist.

Then we can a; Define an object

But when you're going to write this, a * = b;

The compiler does not know that a is the parent class of B, so

It's an error. The simplest way is to include the header file of B.

Pointer to parent class cannot point to child class object

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.