static void function in a class

Hello,

In the tutorial section titled "Inheritance" the last program declares a function in "class Output":

1
2
3
4
  class Output {
  public:
    static void print (int i);
};


Could somebody elaborate on why this function was declared as static?
Normally a function is declared static so you can access it without having an instance of the class. They are special in that they don't have a 'this' pointer, and they can only access static members of the class. For example, you would call that function like this:

Output::print(5);

Of course, without actually seeing the context around that code, I can't tell exactly why they felt the need for a static function in a class, but hopefully you should at least understand what it is and how it might be used.
Last edited on

Here's the entire program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// multiple inheritance
#include <iostream>
using namespace std;

class Polygon {
  protected:
    int width, height;
  public:
    Polygon (int a, int b) : width(a), height(b) {}
};

class Output {
  public:
    static void print (int i);
};

void Output::print (int i) {
  cout << i << '\n';
}

class Rectangle: public Polygon, public Output {
  public:
    Rectangle (int a, int b) : Polygon(a,b) {}
    int area ()
      { return width*height; }
};

class Triangle: public Polygon, public Output {
  public:
    Triangle (int a, int b) : Polygon(a,b) {}
    int area ()
      { return width*height/2; }
};
  
int main () {
  Rectangle rect (4,5);
  Triangle trgl (4,5);
  rect.print (rect.area());
  Triangle::print (trgl.area());
  return 0;
}
Thanks NT3,

In the context of what you are saying that would make sense after looking at the above code.

The code was presented to illustrate the nature of multiple inheritance from a class.

Am I correct in thinking that "static void print (int i);" was stated in class Output so the return values of rect and trgl could be returned via cout as a result of having inherited "static void print (int i);" from Output?

I hope I put that in a way that makes sense...
You could have done Output::print( rec.area() )
It seems that the example was trying to show a misuse of inheritance.
Topic archived. No new replies allowed.