0

Suppose I want mergesort.cpp that implements mergesort. So in my .cpp file I have something like:

int * mergesort(int * a, int lo, int hi)
{
  //mergesort
}

and in the header mergesort.h, I would have:

public static int mergesort(int *, int, int);

Then in another sourcefile, say main.cpp where I included mergesort.h, I would like to call the function mergesort without having to create any instance of an object.

int a [10];
mergesort::mergesort(a,0,9);

Okay, but this doesn't work because I don't know the proper syntax, and I don't really know what terminology to use to ask the question, but hopefully it is clear.

MathStudent
  • 310
  • 2
  • 12
  • There's no type to class an object of, please clarify. Is `mergesort` defined inside a `class` or `struct`? –  Jul 06 '13 at 17:33
  • Search the Web for non-member functions. – nullptr Jul 06 '13 at 17:34
  • Please provide a SSCCE http://sscce.org/ the code sample does not provide enough information. Is `mergesort` part of a class, struct or namespace, if not then you need to drop the `mergesort::` and `public static`. – Shafik Yaghmour Jul 06 '13 at 17:34

3 Answers3

1

I think you're thinking in Java, not C++. In the header you want, simply:

extern int *mergesort(int *, int int);

and in your main.cpp, you would simply call it as:

mergesort(a, 0, 9);
Joe Z
  • 17,413
  • 3
  • 28
  • 39
  • 1
    The `extern` is implicit for function declarations, unless I'm sorely mistaken. Any particular reason you include it? –  Jul 06 '13 at 17:37
  • It's not strictly necessary, agreed. It is a habit I got into as a C programmer years back, to mirror declarations of external variables and objects. Granted, global variables are bad style, but still fairly common in C code. Also, `extern` on a templated function prevents instantiating redundant specializations, so another reason for the habit. – Joe Z Jul 06 '13 at 18:09
1

You don't even need a static modifier in this instance.

//mergesort.h
#ifndef MERGESORT_H
#define MERGESORT_H
int* mergesort(int*, int, int);
#endif

And...

//mergesort.cpp
#include "mergesort.h"
int* mergesort(int * a, int lo, int hi)
{
   // do your thing
}

And later on:

// some other file
#include "mergesort.h"

int main()
{
    int a [10];
    mergesort(a,0,9);    
    return 0;
} 
Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
0

Just put

int mergesort(int *, int, int);

in the header and then call

mergesort(a,0,9);

from your main.cpp and you will be fine.

I suppose that you come from a true object oriented language (such as Java) background, where everything needs to be an object. In C++ a standalone function is perfectly fine. There is also no need for the public and static keywords, since those pertain to classes.

I strongly recommend that you read a C or C++ book. Look here.

Community
  • 1
  • 1
Martin Drozdik
  • 12,742
  • 22
  • 81
  • 146