A question about virtual function

Hello I have a question about virtual function.
I have a base class and a derived class below:

1
2
3
4
5
class Person
{
public:
	virtual void eat() = 0;
};

1
2
3
4
5
6
7
8
9
10
11
12
13
class Student : public Person
{
public:
        Student()
	{
		memset(this, 0, sizeof(Student));
	}
	void eat()override;
};
void Student::eat()
{
	std::cout << "eat breakfast...\n";
}


And I have a main function:
1
2
3
4
5
6
int main()
{
	Student s1;
	s1.eat();
	return EXIT_SUCCESS;
}

I ran this program in VS2022 and when s1's default constructor was called.Its _vfptr was set to 0x0000...
I thought that s1 must call virtual function eat() via its _vfptr and I set its value as 0.But it could still call eat() correctly.I don't know why this happens.Could someone tell me the reason please? Thank you very much!
Last edited on
memset(this, 0, sizeof(Student)); engenders undefined behaviour (Student is not a TriviallyCopyable type).

In s1.eat() there is no virtual call (the function is not called through a pointer or reference); evaluated as s1.Student::eat().
Thank you so much!I get it.
Registered users can post here. Sign in or register to post.