Static Member Inheritance

I am new to C ++ programming, I have doubts about the execution of some C ++ programs, i.e. how to achieve dynamic binding for a static member function. dynamic linking of normal member functions can be achieved by declaring member functions as virtual, but we cannot declare static member functions as virtual, so please help me. and see the example below:

#include <iostream> #include <windows.h> using namespace std; class ClassA { protected : int width, height; public: void set(int x, int y) { width = x, height = y; } static void print() { cout << "base class static function" << endl; } virtual int area() { return 0; } }; class ClassB : public ClassA { public: static void print() { cout << "derived class static function" << endl; } int area() { return (width * height); } }; int main() { ClassA *ptr = NULL; ClassB obj; ptr = &obj ; ptr->set(10, 20); cout << ptr->area() << endl; ptr->print(); return 0; } 

In the above code, I assigned a Derived class object to a pointer and called the print () static member function, but it calls the Base class function in the way that I can achieve dynamic binding for the static member function.

+7
source share
4 answers

The dynamic binding you want is non-static behavior.

Dynamic binding is binding based on the this pointer, and by static functions, by definition, this pointer is not required or required.

Assuming you want the function to be static in other situations (it doesn't have to be static in your example), you can wrap a static function in a non-static function.

 class ClassA { // (the rest of this class is unchanged...) virtual void dynamic_print() { ClassA::print(); } }; class ClassB : public ClassA { // (the rest of this class is unchanged...) virtual void dynamic_print() { ClassB::print(); } }; 
+7
source

So, you have two problems, firstly, you cannot use inheritance with static functions. Secondly, you are missing the virtual keyword to tell the compiler that this function can be overridden by child classes.

So, suppose you are fixing a static problem.

 virtual void print(){...} 
+3
source

Dynamic linking doesn't make much sense, since you don't even need an object to call a static function.

+1
source

You cannot make static methods virtual. Just make the print method virtual (like the area method). This will serve your purpose.

+1
source

All Articles