1.virtual and Static functions
In C + +, static member functions cannot be declared as virtual functions.
For example, the following program will fail to compile.
#include <iostream>
class Test
{public
:
//Compilation error: Static member function cannot be declared as virtual
virtual static void Fun () {}
};
Similarly, static member functions cannot be declared as const and volatile.
The following program will also fail to compile.
#include <iostream>
class Test
{public
:
//Compile Error: Static member function cannot be const
static void Fun () const {}
//If declared as follows, it is OK.
const static void Fun () {}
or similar to
const static int fun () {return 0;}
};
2. Why the static member function cannot be virtual
1. Static members do not belong to any class object or class instance, so even adding virutal to this function makes no sense.
2. there is a major difference between static and non-static member functions. That is, the static member function does not have this pointer .
Virtual functions rely on vptr and vtable to handle them. Vptr is a pointer that creates a build in the constructor of the class and can only access it with the this pointer because it is a member of the class and vptr points to the vtable that holds the address of the virtual function.
For a static member function, it does not have the this pointer, so it cannot access vptr. This is why the static function cannot be virtual.
Call relationship for virtual function: This-> vptr-> vtable->virtual function
The following example allows you to determine that when a class adds a virtual function, the class size increases by 4 bytes (the size of the pointer).
Class Test
{
Public
int _m;
};
sizeof (Test) = 4;
After adding a virtual function,
Class Test
{
Public
int _m;
virtual void fun ();
};
sizeof (Test) = 8
3. Why a static member function cannot be a const function
affects the this pointer when declaring a NON-STATIC member function to be const. For a const-decorated member function in a test class, the this pointer is equivalent to the test const, and for a non-const member function, the this pointer is equivalent to test.
While the static member function does not have the this pointer, it makes no sense to use const to modify the static member function. The same is true of
volatile.
4. Static member functions can only access static member variables-> static member functions do not have this pointer
5. Static members can be accessed independently, that is, they can be accessed without creating any object instances. -> static member functions do not belong to any object, but belong to the class.