Private method exposed?

M

Maluk

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!
 
L

Leor Zolman

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top