-
Notifications
You must be signed in to change notification settings - Fork 0
/
VirtualBaseClassSyntax.cpp
39 lines (36 loc) · 1.37 KB
/
VirtualBaseClassSyntax.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;
class A {
public:
void say()
{
cout << "Hello world"<<endl;
}
};
class B : public virtual A {
};
// you can also write "virtual" key word before accses specifier (public
// private,protected)
class C : virtual public A {
};
class D : public B, public C {
};
int main(){
D a;
a.say();
return 0;
}
/*
The main thing to note here is that the data members and member functions of
class “A” will be inherited twice in class “D” because class “B” and “C” are
the parent classes of class “D” and they both are being derived from class “A.
So when the class “D” will try to access the data member or member function of
class “A” it will cause ambiguity for the compiler and the compiler will
throw an error. To solve this ambiguity we will make class “A” as a virtual
base class. To make a virtual base class “virtual” keyword is used.
When one class is made virtual then only one copy of its data member and
member function is passed to the classes inheriting it. So in our example
when we will make class “A” a virtual class then only one copy of the data
member and member function will be passed to the classes “B” and “C” which
will be shared between all classes. This will help to solve the ambiguity.
*/