-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path43virtualbaseclass.cpp
More file actions
118 lines (108 loc) · 2.6 KB
/
Copy path43virtualbaseclass.cpp
File metadata and controls
118 lines (108 loc) · 2.6 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
CONCEPT OF VIRTUAL BASE CLASS :-
When creating a hybrid setting of inheritance, when a single a class(A) derives 2 classes(B), (C) that derives a single class(D),
the inherited members of class A are inherited in D multiple times, (twice here)
This creates AMBIGUITY
To prevent the ambiguity from happening and inheritance of a member only once to the grandson derived class, we use virtual keyword
to declare that class A is a virtual class and it's members can only be inherited once
*/
#include <iostream>
using namespace std;
class Student
{
protected:
int roll_num;
public:
void set_roll_num(int x)
{
roll_num = x;
}
void print_roll()
{
cout << "Student Roll number is : " << roll_num << endl;
}
};
class Test : virtual public Student
{
protected:
float maths, physics;
public:
void setMarks(float x, float y)
{
maths = x;
physics = y;
}
void print_marks()
{
cout << "Your result is here : Roll Number [ " << roll_num << " ]" << endl
<< "Marks in Maths : " << maths << endl
<< "Marks in Physics : " << physics << endl;
}
};
class Sports : virtual public Student
{
protected:
float score;
public:
void set_score(float sc)
{
score = sc;
}
void print_score()
{
cout << "Here is your score : " << endl
<< score << endl;
}
};
class Result : public Test, public Sports
{
private:
float total;
public:
float setTotal()
{
return (maths + physics + score) / 3;
}
void display(void)
{
print_roll();
print_marks();
print_score();
cout << "Total Marks in Test and Sports combined (MATHS, PHYSICS, SCORE): " << endl
<< setTotal() << endl;
}
};
int main()
{
Result Std1;
Std1.set_roll_num(12);
Std1.setMarks(78.51, 88.23);
Std1.set_score(93);
Std1.display();
return 0;
}
/*
SYNTAX FOR VIRTUAL BASE CLASS
class {{base class name}}
{
class members...
ex: mem1;
};
class {{first derived class name}} : virtual {{visibility mode}} {{base class name}}
{
members...
passed with mem1
};
class {{second derived class name}} : virtual {{visibility mode}} {{base class name}}
{
members...
passed with mem1
};
class {{Multiple inherited class name}} : {{visibility mode}} {{1st derived class}}, {{visibility mode}} {{2nd derived class}}
{
members...
mem1 is passed down here twice but,
due to virtual keyword the compiler understands that the mem1 is needed to be passed down here just once
hence, ambiguity is prevented
}
*/