Important and easy to ignore issues in class design in C ++

Source: Internet
Author: User

Important and easy to ignore issues in class design in C ++
Consider the following:ProgramOutput result
# Include <stdio. h>
Class baseclass
{
Public:
Baseclass ()
{
Fun (); // is fun of the base class or fun of the derived class called here?
}
Virtual void fun ()
{
Printf ("call basic functions fun/N ");
}
Void test ()
{
Fun (); // is fun of the base class or fun of the derived class called here?
}
};

Class deriveclass: Public baseclass
{
Public:
Virtual void fun ()
{
Printf ("Call the derived class function fun/N ");
}
};

Int main ()
{
Deriveclass D;
D. Test ();
Return 0;
}

Many may come up with the following results:
Result 1:
Call the function fun of a derived class.
Call the function fun of a derived class.
Result 2:
Call basic functions fun
Call basic functions fun

Unfortunately, both results are incorrect!
The correct result should be:
Call basic functions fun
Call the function fun of a derived class.

Why is this? If a base class constructor calls a virtual function, it only calls the base class function and cannot call the function of the derived class.
Why? Check the changes.
# Include <stdio. h>
Class baseclass
{
Public:
Baseclass ()
{
Fun (); // is fun of the base class or fun of the derived class called here?
}
Virtual void fun ()
{
Printf ("call basic functions fun/N ");
}
Void test ()
{
Fun (); // is fun of the base class or fun of the derived class called here?
}
};

Class deriveclass: Public baseclass
{
Int N;
Public:
Virtual void fun ()
{
N = 0;
Printf ("Call the derived class function fun/N ");
}
};

Int main ()
{
Deriveclass D;
D. Test ();
Return 0;
}

If the base class constructor calls the derived class function fun, this can be broken. Because the base class is constructed prior to the derived class, the N of the derived class has not yet, and the base class must assign a value to I, obviously, this is ridiculous. Therefore, this design is unreasonable.
I hope these things will be useful to everyone.

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.