[Original] discussion of declaring the private member function of the base class as a virtual function

Source: Internet
Author: User

Some people think that "virtual is used to declare a polymorphism as private is meaningless." "Private: the visible domain is the class itself, and the derived class is invisible !"

I thought so at first, but after I did the experiment, I found that this was not the case (Code environment vc6.0)

Interface itest
{
PRIVATE:
Virtual void test () = 0;
}

Class ctest: Public itest

If the test member function is not defined in ctest, it cannot be compiled.

If it is defined, but it cannot be called using the itest: test method, ctest: test can still be called.

Therefore, even if private is defined, polymorphism can still be implemented in the derived class.

Is this the case only for pure virtual functions? You have done the following experiments:

Class itest
{
Public:
Void Test2 (){
Test ();
}
PRIVATE:
Virtual void test (){};
};

Class ctest: Public itest

The call is as follows:
Itest * Ptest = (itest *) This;
Ptest-> Test2 ();

If you implement the test function in ctest, ctest: test will still be called.

It can be seen that although the subclass cannot directly call the private function of the parent class, it can be overloaded and the constraints of the function can be modified (from private to public ).

Someone asked: "polymorphism does not use 'base class pointer or reference to call the function of a derived class '. Since it is impossible to call ctest: test through itest, how is it called 'implement polymorphism in a derived class '?"

I think this is a very radical idea. For example, in the above example, some code in Test2 can be implemented using test. I can use a derived class to make the test multi-state. What can the compiler support, only polymorphism is manifested in the class.

Finally, I would like to thank csdn.net's zhpzh (seeking for new ideas) for asking this question. I really don't want to think of it myself. I will sort out the answers and post them for your reference.

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.