In C++, virtual function is defined as a member function in a class from which other classes may be derived. If the derived class has a function with the same name and parameter list, the derived class's function is always executed for objects of the derived class. We have to use virtual class in the base class for defining this function in the base class.
Let's understand this concept with the help of the following example:
#include<iostream.h>
#include<conio.h>
class A
{
public:
char Avar;
void show()
{
cout<<"i 'm A"< }
};
class B : Virtual Public A
{
public:
void show()
{
cout<<"i 'm B"< }
};
class C : Virtual Public A
{
Public:
void show()
{
cout<<"i 'm C"< }
};
class D : Class B, Class C
{
Public:
void show()
{
cout<<"i 'm D"< };
int main()
{
D Dtemp;
Dtemp.show();
getch();
RETURN 0;
}
In the preceding example, the classes B and C use the virtual keyword to inherit the members of class A. Therefore, class A is the virtual base class and class D inherits only one copy of the member data Avar from class A. Therefore, any reference to the member Avar through an object of class D does not lead to ambiguity.
Let's understand this concept with the help of the following example:
#include<iostream.h>
#include<conio.h>
class A
{
public:
char Avar;
void show()
{
cout<<"i 'm A"<
};
class B : Virtual Public A
{
public:
void show()
{
cout<<"i 'm B"<
};
class C : Virtual Public A
{
Public:
void show()
{
cout<<"i 'm C"<
};
class D : Class B, Class C
{
Public:
void show()
{
cout<<"i 'm D"<
int main()
{
D Dtemp;
Dtemp.show();
getch();
RETURN 0;
}
In the preceding example, the classes B and C use the virtual keyword to inherit the members of class A. Therefore, class A is the virtual base class and class D inherits only one copy of the member data Avar from class A. Therefore, any reference to the member Avar through an object of class D does not lead to ambiguity.
No comments:
Post a Comment