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 is interface in oop?

664


Get me an image implementation program.

1563


What is static in oop?

591


Why is polymorphism needed?

605


Which method cannot be overridden?

584






what is difference between class template and template class?

2163


Give an example where we have to specifically use C programming language and C++ programming language cannot be used?

1153


What are two types of polymorphism?

616


Which is better struts or spring?

624


What is an example of genetic polymorphism?

653


What is coupling in oop?

604


Can a varargs method be overloaded?

619


What is advantage of inheritance?

694


class type to basic type conversion

1843


What is encapsulation selenium?

557