static member functions inheritance
Asked Answered
I

4

8

I am new to C++ programming, i have a got doubt while doing some C++ programs, that is how to achieve dynamic binding for static member function. dynamic binding of normal member functions can be achieved by declaring member functions as virtual but we can't declare static member functions as virtual so please help me. and please see the below example:

#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 have assigned Derived class object to a pointer and calling the static member function print() but it is calling the Base class Function so how can i achieve dynamic bind for static member function.

Ipswich answered 15/5, 2013 at 5:39 Comment(0)
I
8

The dynamic binding that you want is a non-static behavior.

Dynamic binding is binding based on the this pointer, and static functions by definition don't need or require a this pointer.

Assuming that you need the function to be static in other situations (it doesn't need to be static in your example) you can wrap the 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();
     }
};
Ic answered 15/5, 2013 at 5:47 Comment(0)
F
3

So you have two issues here, the first is that you can't use inheritance with static functions. The second is that you are missing the keyword virtual to tell the compiler that this function can be overridden by child classes.

So assuming you fix the static problem.

virtual void print(){...}
Fortnightly answered 15/5, 2013 at 5:47 Comment(0)
O
1

Dynamic binding doesn't make much sense since you don't even need an object to call the static function.

Obumbrate answered 15/5, 2013 at 5:44 Comment(0)
A
1

You can't make static methods as virtual. Just make print method as virtual (just like area method). It would serve your purpose.

Ampoule answered 15/5, 2013 at 5:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.