PROGRAM1:
Class a{
Public
void print () {cout<< "This is A" <<ENDL;}
};
Class B:public a{
Public
void print () {cout<< "This is B" <<ENDL;}
};
int main () {
A;
b b;
A.print ();
B.print ();
}
Output:
This is A
This is B
PROGRAM2:
int main () { //main2
A;
b b;
A * p1=&a;
A * p2=&b;
P1->print ();
P2->print ();
}
Output:
This is A
This is A
PROGRAM3:
Class a{
Public
virtual void print () {cout<< "This is A" <<ENDL;} Now it's a virtual function.
};
Class B:public a{
Public
void print () {cout<< "This is B" <<ENDL;} Do you need to add the keyword virtual to the front?
};
Output:
This is A
This is B
Dry:
If the child class overrides the virtual function of the parent class
A pointer to the parent class, or a reference to an object that actually points to the child class
When a virtual function is called through the pointer or reference, the (virtual) function of the subclass is called
If it is not a virtual function, the function of the parent class will be called
Example of C + + virtual function usage