My question is very similar to a previously answered question except I'm trying to rewrite the same program using seperate compilation in order to practice proper C++ coding style. I've simplified the program to highlite the problamatic areas.
Currently this program runs fine if I declare the entire class as a friend, but this feels inherently dangerous, giving the entire class friend access.
File Foo.h
#ifndef FOO_H
#define FOO_H
class Foo{
friend class Bar;
public:
// getX defined in header for simplicity.
const int &getX() const{
return x;
}
private:
int x = 0;
};
#endif
File Bar.h
#ifndef BAR_H
#define BAR_H
#include "Foo.h"
class Bar{
public:
void mutateX(Foo &foo);
};
#endif
File Bar.cpp
#include "Bar.h"
void Bar::mutateX(Foo &foo){
foo.x = 1;
}
I can't wrap my head around how to just make the mutateX member as a friend. Any help will be greatly appreciated!
Here's a tester class main.cpp
#include "Foo.h"
#include "Bar.h"
#include <iostream>
int main(){
Foo foo;
Bar bar;
std::cout << foo.getX() << std::endl;
bar.mutateX(foo);
std::cout << foo.getX() << std::endl;
return 0;
}