Toastbot
Toastbot

Reputation: 87

Can i call a class in my function within said class?

since i´m a littlebit rusty in c++ and classes i´m not sure if i just do some major mistakes or if it´s just not possible, maybe anyone here can make me smarter.

I´m trying to make a compare function for my "possition" class. So that i can later call pos1.compare(pos2) and get a bool back. For some reason it does not compile, and i think it might be bcuz i try calling the class inside itself?

I use c++, windows and i compile with minGW.

class myPossition{
  public:
    int x;
    int y;
  private:
    myPossition( int nx, int ny ){
        x = nx;
        y = ny;
    }
    bool compare( myPossition compPos ){
        if(compPos.x==x&&compPos.y==y)return true;
        return false;
    }

};

Upvotes: 0

Views: 33

Answers (1)

Vladimir Nikitin
Vladimir Nikitin

Reputation: 181

I will assume that by "not working" you mean you wrote code like:

int main() {
    myPosition a(1, 2);
    myPosition b(3, 4);
    std::cout << a.compare(b) << std::endl;
}

And it didn't compile. The answer is you should put both myPosition( int nx, int ny ) and bool compare( myPosition compPos ) into public section, not private.

You can read more about access specifiers here https://en.cppreference.com/w/cpp/language/access

Upvotes: 1

Related Questions