Shishir Sharma wrote:
> #include <iostream>
>
> using namespace std;
>
> class Base {
> public:
> virtual void display() {
> cout<<"Hi I Am Foo, I Am In Base Class"<<endl;
> }
> };
>
> class Derived : public Base {
> private:
> void display() {
> cout<<"Hi I Am Foo, But Now I Am In Derived
> Class"<<endl;
> }
> };
>
>
> int main() {
>
> Base * B = new Derived;
>
> B->display();//U can access Derived class Private Member
> function using add;
> //but if u use Derived class pointer it doesn't work.
> //This is violation of object oriented concepts ...
> return 0;
> }
>
> //Thanks
>
>
> //i got this ex. in a diffrent group
I don't see how this is a "violation of OOP". You are asking a public
member of the base class to execute a virtualized function - virtual
base class functions call the most derived function of same name and
parameters. Most implementations use a vtable...whatever address the
function points at is the one that gets called. It seems that you are
asking for runtime checking of sections, which would most likely result
in a huge performance hit. If you want the function only available to
derived classes, then it should be declared in a 'protected:' section in
the base class. If you need it public in some classes and private in
others, you can change the section type via a derived class. That will
move checking of section types to compile-time and not affect runtime
performance.
BTW, the 'Derived' class member function display() is written
incorrectly. It should have the 'virtual' keyword to avoid weird
problems. Also, both classes should have a virtual destructor so they
are destroyed properly. You don't 'delete' the object so you leak
memory (but the OS will clean it up). Finally, you have the 'new'
keyword at the application layer. 'new/delete' belong at the base
library layer.
--
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197
*NEW* MyTaskFocus 1.1
Get on task. Stay on task.
http://www.CubicleSoft.com/MyTaskFocus/