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.