-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path44derivedconstr.cpp
More file actions
83 lines (73 loc) · 2.31 KB
/
Copy path44derivedconstr.cpp
File metadata and controls
83 lines (73 loc) · 2.31 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
/*
CONSTRUCTORS IN DERIVED CLASSES
For different kinds of inheritance, a constructor call order is followed like:
in Multi-level inheritance, the constructor call starts from the first created base class to the derived base class till
the final derived class whose object is created
in Multiple inheritance, the order of declaration of base class in derived class determines whose constructor is called first
eg :- class {{derived class}} : {{visibility mode}} {{base class 1}}, {{visibility mode}} {{base class 2}}
ORDER OF CONSTRUCTOR CALL : Base 1 --> Base 2 --> Derived
class {{derived class}} : {{visibility mode}} {{base class 2}}, {{visibility mode}} {{base class 1}}
ORDER OF CONSTRUCTOR CALL : Base 2 --> Base 1 --> Derived
in case of a virtual class, it has the highest preference order
{{derived class}} : {{visibility mode}} {{base class 2}}, virtual {{visibility mode}} {{base class 1}}
ORDER OF CONSTRUCTOR CALL : Base 1 --> Base 2 --> Derived
special syntax for derived class constructor
{{derived class name}} (arg1, arg2, arg3, ....) : {{base1}}(arg1, arg2...), {{base2}}(arg3, arg4...)...
*/
#include <iostream>
using namespace std;
class A
{
int data;
public:
A(int x)
{
data = x;
cout << "Marks the constructor call of class A" << endl;
}
void displayA()
{
cout << "A class data is : " << data << endl;
}
};
class B
{
int data2;
public:
B(int x)
{
data2 = x;
cout << "Marks the constructor call of class B" << endl;
}
void displayB()
{
cout << "B class data is : " << data2 << endl;
}
};
class C : public A, public B
{
int data3, data4;
public:
C(int x, int y, int z, int w) : A(x), B(y) // the order here doesn't matter it doesn't change the constructor call
{
data3 = z;
data4 = w;
cout << "Marks the constructor call of class C" << endl;
}
void displayC()
{
displayA();
displayB();
cout << "C class data is : " << data3 << ", " << data4 << endl;
}
};
int main()
{
C obj(1, 2, 3, 4);
obj.displayC();
return 0;
}
/*
When there are parameters in the base/parent class, then it is necessary to give arguments to the derived class object
otherwise, no need to pass arguments
*/