On Sat, 3 Apr 2004 01:38:51 +0800, "Maluk" <ma***@fromru.com> wrote:
I was wondering why something like this is allowed by the standard.
--- code ---
// Implementation ommitted.
class Base
{
public:
virtual void someFunction ( void ) ;
}
class Derived
{
private:
void someFunction ( void ) ;
}
int main ( void )
{
Derived d ;
Base* pb ;
pb = &d ;
pb->someFunction( ) ; // This calls Derived :: someFunction( )!
}
Now, Derived's private function is made available to the world through a
pointer to the base!
Yes, but your base class specification is misrepresenting the nature of
your hierarchy. You can't really say a Derived "is a" Base if it doesn't
provide Base functionality directly; i.e., you can't say:
Derived d;
d.someFunction();
So if you want to provide a hidden implementation of something, use a
virtual dispatch scheme:
#include <iostream>
using namespace std;
class Base
{
public:
void someFunction()
{
someFnImpl();
}
protected:
virtual void someFnImpl() = 0; // or it may contain
// common functionality
};
class Derived1 : public Base
{
private:
void someFnImpl ()
{
cout << "Derived1::someFnImpl()" << endl;
}
};
class Derived2 : public Base
{
private:
void someFnImpl ()
{
cout << "Derived2::someFnImpl()" << endl;
}
};
int main ()
{
Derived1 d1 ;
Derived2 d2;
Base* pb;
pb = &d1;
pb->someFunction( ) ;
pb = &d2;
pb->someFunction( ) ;
return 0;
}
Output:
Derived1::someFnImpl()
Derived2::someFnImpl()
-leor
--
Leor Zolman --- BD Software ---
www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html