0

So, I am fairly new to C++ OOP and am stuck with this (trivial) problem. I have a class definition with a custom comparator like this:

class Solution {
public:
    static int pos[30];
    static bool cmp(char c1 ,char c2){
        return pos[c1 - 'a'] < pos[c2 - 'a'];
    }
    string customSortString(string S, string T) {
        for(int i = 0 ; i < S.length() ; i++){
            pos[S[i] - 'a'] = i;
        }
        sort(T.begin() , T.end() , cmp);
        return T;
    }
};

I get the error from the compiler

undefined reference to `Solution::pos'

I reckon this has to do with accessing static variable pos inside non-static method customSortString but replacing pos with Solution::pos still doesn't help. What am I doing wrong ?

Always_Beginner
  • 2,546
  • 6
  • 25
  • 33
  • 1
    *I get the error from the compiler* -- not quite. It is your *linker* , not *compiler*, giving you this error. – Geezer Sep 16 '18 at 08:21
  • A better solution here would be to get rid of the static to begin with. If you're learning about OOP, you should be learning not to use static. – Claus Jørgensen Sep 16 '18 at 08:21
  • @SkepticalEmpiricist interesting , also I am reading the reason behind it :/ – Always_Beginner Sep 16 '18 at 08:22
  • 1
    To be honest, I don't really see any reasons for classes here. C++ is not Java, where everything *must* be in classes. In C++ you don't have to use classes. If a problem don't require classes (like your most likely doesn't) then my recommendation is not to use them. – Some programmer dude Sep 16 '18 at 08:35
  • 1
    @Someprogrammerdude - It looks to me like raw code from a training site (where one inputs the solution into an online textbox). Those often put one's code into a `Solution` class. It's a good way to deter solutions that rely on static data, if that is inadmissible. – StoryTeller - Unslander Monica Sep 16 '18 at 08:44

0 Answers0