I'm starting a new project and I have trouble with accessing protected methods of Organism
inside World
class. I suppose there must be some error with my definition of World
being a friend of organism
. I tried calling some method from Organism inside World, but the compiler says that it is inaccessible. The method was of course set as protected, so only derived classes and friends could call them.
World.h:
#include <vector>
#include <iostream>
using std::vector;
#include <map>
using std::map;
#include "Organism.h"
#pragma once
class World
{
private:
map<int, std::shared_ptr<Organism>> organims_map;
vector <std::shared_ptr<Organism>> animals_vector;
int x_size, y_size;
void initiate_aniamals();
public:
World();
World(int x, int y);
void make_turn();
};
Organism.h:
#pragma once
#include "World.h"
class Organism
{
friend class World;
private:
int strength, vigor;
int x_pos, y_pos;
float level;
protected:
int get_vigor() const;
virtual void action() = 0 ;
virtual void collision() = 0;
/// <summary>
/// compares animals by their vigor
/// </summary>
/// <param name="other organism"></param>
/// <returns>which animal has higher vigor</returns>
bool operator<(const Organism& other_organism);
};
Then In file world.cpp i try to define method make_turn():
void World::make_turn()
{
//stable sort animals by their vigor
std::stable_sort(begin(this->animals_vector), end(this->animals_vector),
[](const Organism& organism_1, const Organism& organism_2)
{
return organism_1.get_vigor(); //
});
I get error in line:
return organism_1.get_vigor();
says that function get_vigor is inacessible.
CodePudding user response:
The problem was the fact that #pragma once
was not at the beginning of World.h
But after including Organism.h
. That leads to tons of weird errors including the fact that despite being friends of Organism
, World
couldn't use its private methods.
This is correct:
#pragma once
#include "Organism.h"
This, however is absolutely not:
#include "Organism.h"
#pragma once