I'm having trouble understanding what is the purpose of the keyword virtual
in C ++ C and Java know very well but I am new to C ++
From Wikipedia
In object-oriented programming, there is a virtual function or virtual method Function or method whose behavior is overridden in a inheritance class by a function with a signature Can.
However, I can override one method seen without using virtual
keyword
#include & lt ; Iostream & gt; using namespace std; Class A {public: int a (); }; Int A :: a () {Return 1; } Class B: A {public: int a (); }; Int B: A () {Return 2; } Int main () {B b; Cout & lt; & Lt; B.A. () & Lt; & Lt; Endl; Return 0; } // Output: 2
As you can see below, the function is successfully overridden with A: A: virtual
As explained in the following example, to ensure that the C ++ base class It is important to be a virtual designer for the most derivative category. Will be told.
Then virtual
also tells the compiler to call the parents' killers? From my basic understanding of virtual
it looks very different that "make the function overrunable"
Make the following changes and you will see why:
#include & lt; Iostream & gt; using namespace std; Class A {public: int a (); }; Int A :: a () {Return 1; } Category B: Public A {// Notification Public Added here: int a (); }; Int B: A () {Return 2; } Int main () {A * b = new B (); // Notice we are using a base class pointers cout & lt; & Lt; B-> A () & lt; & Lt; Endl; // It will print 2 instead of 2 removed b; // Removed for Free B return; 0; }
Now, to do things like yours:
#include & lt; Iostream & gt; using namespace std; Class A {Public: Virtual Int a (); // notice virtual added here}; Int A :: a () {Return 1; } Category B: Public A {// Information Public Added here: Virtual int a (); // notice is added here virtual, but not required in C ++}; Int B: A () {Return 2; } Int main () {A * b = new B (); // Notice we are using a base class pointers cout & lt; & Lt; B-> A () & lt; & Lt; Endl; // It will print 2 as a desired print; // Removed for Free B return; 0; }
Note that you have included about virtual installers, OK. There is nothing in your sample that needs to be cleaned, but say that both were a disaster in A and B. If they are not marked virtual, which is going to call the base class pointers? Hint: This will work in exactly the same way that () was done as a method when the virtual was not marked.
No comments:
Post a Comment