Search code examples
c++classoopstaticprivate

Error when using public member function to access private member variable: Variable "was not declared in this scope"


Update for anyone having trouble returning multidimensional arrays

Further reading: Returning multidimensional array from function

I've declared a static int variable in my header. I've defined it in the .cpp file (Implementation file?), as shown with the relevant code below...

Card.h

#ifndef CARD_H
#define CARD_H

class Card {
private:
    static int  _palette[][3];
public:
    static int  palette();
};

#endif /* CARD_H */

Card.cpp

int Card::_palette[][3]=    {
    {168, 0,   32},
    {228, 92,  16},
    {248, 216, 120},
    {88,  216, 84},
    {0,   120, 248},
    {104, 68,  252},
    {216, 0,   204},
    {248, 120, 248}
};

static int palette(){
    return _palette;
}

But when I compile, I get this error:

..\source\src\Card.cpp: In function 'int palette()':
..\source\src\Card.cpp:42:9: error: '_palette' was not declared in this scope
  return _palette;

Shouldn't my accessor function palette() be able to get the value of private member _palette?


Solution

  • You forgot the Card::

    int (*Card::palette())[3]{
        return _palette;
    }
    

    You shouldn't have static in the method definition. Also, you're trying to return an int[][] when you should return an int.

    Change your class to this:

    class Card {
    private:
        static int  _palette[][3];
    public:
        static int  (*palette())[3];
    };