What is Virtual Keyword?

Answer Posted / jyoti bajaj

virtual keyword can be used with base classes as well as
with functions.Here we are talking about virtual base
classes.
class A
{
public:
A(){cout<<"it is class A"<<endl;}
};
class B:public A
{
public:
B(){cout<<"it is class B"<<endl;}
};
class C:public A
{
public:
C(){cout<<"it is class C"<<endl;}
};
class D:public B,public C
{
public:
D(){}
};
void main()
{
D obj;
}
output:
it is class A
it is class B
it is class A
it is class C

since class A is constructed twice.but if we want that only
one copy of class A should be shared by both classes A &
B.so we inherit the base class by using virtual keyword.

class A
{
public:
A(){cout<<"it is class A"<<endl;}
};
class B:virtual public A
{
public:
B(){cout<<"it is class B"<<endl;}
};
class C:virtual public A
{
public:
C(){cout<<"it is class C"<<endl;}
};
class D:public B,public C
{
public:
D(){}
};
void main()
{
D obj;
}
output:
it is class A
it is class B
it is class C

Is This Answer Correct ?    5 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the three parts of a simple empty class?

1740


Why do we need oop?

861


What is the fundamental idea of oop?

835


What is constructor overloading in oop?

831


Can we have inheritance without polymorphism?

774


What is a null tree?

838


What is an advantage of polymorphism?

807


What is difference between pop and oop?

788


What is the use of oops?

780


What are the 3 principles of oop?

812


What is object and class in oops?

772


What is the difference between abstraction and polymorphism?

823


i got a backdoor offer in process global,Bangalore..Can i work with it?

2564


how to get the oracle certification? send me the answer

1881


What is oops and why we use oops?

767