Let me show you the simple C++ code example first.
#include <iostream>
using namespace std;
class Person{
string m_name;
public:
virtual void saySomething(){
cout << "I am a person.";
}
};
class Student:public Person{
public:
void saySomething(){
cout << "I am a student." << endl;
}
};
class CSStudent:public Student{
public:
void saySomething(){
cout << "I am a CS Student." << endl;
}
};
int main(){
Person* p = new Person();
Student* s = new Student();
CSStudent* c = new CSStudent();
((Student*)c)->saySomething();
return 0;
}
In my example, Student is a derived class of Person. Also, CSStudent is a derived class of Student. I know virtual keyword make it possible to determine if it is derived class.
Question 1.
((Student*)c)->saySomething();
Why do I get "I am a CS Student."? I expected "I am a Student." since I specify virtual keyword only for the Person.
Question 2.
I saw an example that puts a virtual keyword to only base case. Also, I saw an example that puts virtual keywords to all base case and derived classes. What's the difference between these two?
Question 3.
virtual function is determined in run time. What about non-virtual function? Is it determined in compile time?