Virtual key word

Can access any private member of the base class through the derived class FUNCTION IF IT IS VIRTUAL?

Questions by saquib_225

Showing Answers 1 - 12 of 12 Answers

jezpops

  • Jul 7th, 2008
 

I dont understand what you want to do by this question. Usually the virtual keyword would be used in the base class and the method overridden in the derived class.

The virtual keyword ensures that the correct overridden function in the derived class is called rather than the function in the base class. It ensures only one instance of the object exists at runtime.

Since it only usually used in inheritance then methods of the base class would be accessible anyway (dependent on the access specifiers)

  Was this answer useful?  Yes

arun_goel3

  • Jul 15th, 2008
 

using typecasting and virtual we can access the private member of base class

#include <iostream>

using namespace std;

class base

{

int i;virtual void update(int j)

{

cout << "in base update" << endl;

i = j;

}

public :

base ( int ii = 10) : i(ii) {}

void print()

{ cout << "value of i " << i << endl; }

virtual ~base() {}

};

class derived : public base

{

public :

int i;derived (

int i1 = 20, int i2 = 21) : base(i1) , i(i2) {}virtual void update(int j)

{

cout << "in derived update" << endl;

i = j;

}

};

void main()

{

base *b1 = new base();

b1->print();

derived *d = (derived *)b1;

d->update(30);

b1->print();

delete b1;

}

  Was this answer useful?  Yes

No way,
Ex:
#include<iostream>
using namespace std;
class base{
    private:
        int a;
    public:
        virtual void show()
        {
            cout<<a<<endl;
        }
};
class derived:public base{
    public:
        void display()
        {
            cout<<a<<endl;//we must call show() here instead
        }
};
int main()
{
    derived ob;
    ob.display();
    return 0;
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions