You can't do that with inheritance. Given a pointer to baseclass
, the compiler only knows it has a public
virtual
function, so allows calling the function accordingly.
The derived class has elected to inherit from the base class, and has implemented a function with different access. But none of that is visible, given only a pointer to the base.
There is nothing preventing derivedclass::printmynumber()
from being implemented to do nothing - which means if code calls it, there will be no observable effect (assuming absence of an expected effect is tolerable).
The real solution is to fix your design, not to try to work around deficiencies in it. Don't inherit derivedclass
from baseclass
. That way, no member function of derivedclass
can be called at all, given only a pointer to baseclass
, since the types are not related (passing a derivedclass *
to a function expecting a baseclass *
will normally be diagnosed as an error).
BTW: main()
returns int
, not void
. Some compilers support void main()
as a non-standard extension (and the documentation for some of those compilers falsely describes such a thing as standard) but it is better avoided.