20

I can't get past this issue I am having. Here's a simple example:

class x
{
    public:
    void function(void);

    private:
    static void function2(void);
};

void x::function(void)
{
    x::function2(void);
}

static void function2(void)
{
     //something
}

I get errors in which complain about function2 being private. If I make it public (which I don't really want to do) I get errors about an undefined reference to function2. What am I doing wrong? Thank you!

Suzanne Soy
  • 3,027
  • 6
  • 38
  • 56
Alex
  • 426
  • 1
  • 6
  • 15

2 Answers2

36
  1. You can't have a function declaration and definition both in a class. Either move the definitions out of the class or remove the declarations.

  2. You can't call a function with a void as a parameter. That is used only in the declaration.

  3. The function definition for function2 if outside the class will need a x:: qualifier and static is not needed the second time.


    class x
    {
        public:
            void function(void); 
        private:
            static void function2(void);
    };

    void x::function(void)
    { 
        x::function2(); 
    }

    void x::function2(void)
    {
    }
Sameer
  • 725
  • 5
  • 8
  • It was because I had static the second time. My example was bad, but thank you very much. – Alex Mar 22 '10 at 00:19
3

You must define function2 with

static void x::function2 (void)
{
    body
}

as it was with x::function

update: Yes. you don't need to mark class method with static when defining it.

class x
{
 public:
   void function(void);

 private:
   static void function2(void);
}; //end of class

// here are definitions of members
static void x::function(void)
{
  x::function2();
}
static void x::function2(void)
{
//something
}
osgx
  • 90,338
  • 53
  • 357
  • 513
  • 2
    That gives me this error: cannot declare member function to have static linkage. Did I make an error elsewhere? – Alex Mar 22 '10 at 00:11
  • 4
    Under g++-v4.7, it seems you _must_ leave out the keyword "static" when implementing the function. – Joachim W Aug 25 '13 at 11:10