c++ - Calling derived class function without marking it as virtual from a class in middle in multi-level inheritance -
I think this may be a repetitive question, but I tried to read almost all related posts and none of them Not even specific was what I was looking for.
OK, so I understand that unless virtual is marked, you can not call a function in a class derived from a base class pointer. Like reference program 1, this B class can not call 'Kaunasclass () if no virtual is marked.
# include & lt; Iostream & gt; using namespace std; Class A {public: const char * Which square () {return "A";}}; Class B: Public A {Public: const char * Which square () {return "B";}}; Int main () {B b; A and A = B; Cout & lt; & Lt; "In class" & lt; & Lt; A.Which class (); Return 0; } If I mark it as a virtual one, then it tells the work of the most derived class from the base class. Now suppose that if I connect B to the second class C (as shown in program 2), and if class B is not marked as virtual, then how the base reference (& A) Call Class C? Additionally, with class B reference (amp; b), which class can call in C. When it is not marked as classical in class B according to what we saw in program 1?
Add # & lt; Iostream & gt; using namespace std; Class A {Public: Virtual Conservative Characters • Which Class () {Return "A";}}; Class B: Public A {Public: const char * Which square () {return "B";}}; Class C: Public B {Public: const char * WhichClass () {Return "C";}}; Int main () {cc; A and A = C; B & amp; B = C; Cout & lt; & Lt; "In class" & lt; & Lt; A.Which class () & lt; & Lt; Endl; Cout & lt; & Lt; "In class" & lt; & Lt; B.WhichClass () & lt; & Lt; Endl; Return 0; }
Because when you create a virtual virtual method in the base class and the base class Creates an indicative point to a derived class, then in that case it calls the most derived class function. In your case you have,
A & A = C; Here the indicator square of A base class A is pointing to C, so when you call the class () method, the method of class C is called. B & B = C; Even here when you call a function using base class pointers, the function of the highest derived class is said based on which class you point to. In this case, the indicator of class B is pointing to the object of C, then which class (class) method of class C will be called. For more details, please check it out,
Comments
Post a Comment