Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Functions in C++

Tags:

I've read a few posts on here about static functions, but still am running into trouble with implementation.

I'm writing a hardcoded example of Dijkstra's algorithm for finding the shortest path.

Declared in Alg.h:

static void dijkstra(); 

Defined in Alg.cpp:

static void Alg::dijkstra() {   //Create Map Initialize();  //Loop to pass through grid multiple times for(int i=0; i<5; i++) {        current=1;       while(current!=6)     {         //Iterate through and update distances/predecessors         //For loop to go through columns, while current iterates rows         for(int j=1; j<7; j++)         {             //Check if distance from current to this node is less than             //distance already stored in d[j] + weight of edge              if(distanceArray[current][j]+d[current]<d[j])             {                 //Update distance                 d[j] = distanceArray[current][j]+d[current];                 //Update predecessor                 p[j] = current;             }             }         //Go to next row in distanceArray[][]         current++;     } //End while   } //End for  output(); } //End Dijkstras 

I want to call my function from main without an object. When I had all of this code in Main.cpp, it worked perfectly. Splitting it up into separate files caused the error Main.cpp:15: error: ‘dijkstra’ was not declared in this scope.The posts I came across when searching SE gave me me the impression that to do this, I needed to make that method static, yet I still have no luck.

What am I doing wrong?

Main.cpp:

#include <iostream> #include "Alg.h"  int main() {       dijkstra();     return 0;  } 

Edit: Added full header file, Alg.h:

#ifndef Alg_ #define Alg_  #include <iostream> #include <stack>  using namespace std;  class Alg {     public:         void tracePath(int x);         void output();         void printArray();         void Initialize();         static void dijkstra();         int current, mindex;         int distanceArray[7][7]; //2D array to hold the distances from each point to all others         int d[6]; //Single distance array from source to points         int p[6]; //Array to keep predecessors          int copyD[6]; //Copy of d[] used for sorting purposes in tracePath()         int order[6]; //Contains the order of the nodes path lengths in ascending order  }; //End alg class  #endif 

Original all-in-one working Main.cpp file: http://pastebin.com/67u9hGsL

like image 962
Ladybro Avatar asked Dec 03 '13 22:12

Ladybro


1 Answers

You should call it this way:

Alg::dijkstra(); 

Limitations

  • Can't call any other class functions that are not static.
  • Can't access non static class data members.
  • Can instantiate an object via new class() when constructor is private/protected. E.g. a factory function.
like image 192
egur Avatar answered Nov 07 '22 12:11

egur