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?

1458


Why do we use inheritance?

628


What does oop mean in snapchat?

680


Can a destructor be called directly?

599


Is this job good for future? can do this job post grduate student?

1689






What is destructor example?

595


Can enum be null?

585


What is encapsulation c#?

600


Can we have inheritance without polymorphism?

608


What do you mean by variable?

572


Why is oop better than procedural?

602


I have One image (means a group photo ) how to split the faces only from the image?............ please send the answer nagadurgaraju@gmail.com thanks in advace...

1626


Can static class have constructor?

582


What type of loop is a for loop?

682


Why is abstraction used?

603