Tuesday, 4 June 2013

Virtual Keyword

class A{
public:
void hello(){
cout<<"hello from A";
}
}

class B:public A{
public:
// over riding method hello from A
void hello(){
cout<<"hello from B";
}
}

void main(){
A *a; // reference of A
B b; // object of B
a=&b; // reference of  A pointing to B object
a->hello();
}

Output of the above code:
hello from A

But if we make hello method in class A virtual then the output will be "hello from B".

and if the method hello in class A is written as

void hello(); (i.e no definition is given)  then this method is called pure virtual function.


There is also a concept of virtual base class.

class A{
public :
int i;
}
class B:virtual public A{
}
class C:virtual public A{
}
class D: public B,C{
}

Here class B and C virtually inherits A and class D inherits B and C both. So there will be only one copy of i in class D.
Here class A is called virtual base class.

No comments:

Post a Comment