Let's say I have the following classes:
Trees and wood;
Object trees contain an array of Tree objects.
Here are the contents of the tree and tree classes:
Trees.h:
#pragma once
#include "Tree.h"
class Trees
{
private:
Tree m_Tree[20];
int iTrees;
public:
Trees(void) : iTrees(0){}
Tree GetTree(int i){ return m_Tree[i];}
void AddTree(Tree tree){ m_Tree[iTrees++] = tree;}
};
tree.h:
#pragma once
#include <string>
class Tree
{
private:
std::string Name;
bool HasRelatives;
public:
Tree(void):HasRelatives(0){};
Tree(std::string name):Name(name), HasRelatives(0){};
std::string GetName(){ return Name;}
void SetName(std::string name){ Name = name;}
bool GetHasRelatives(){ return HasRelatives;}
void SetHasRelatives(bool alone){ HasRelatives = alone;}
bool operator == (Tree & tree)
{
if(this->GetName() == tree.GetName())
{
this->SetHasRelatives(1);
tree.SetHasRelatives(1);
return 1;
}
return 0;
}
};
And let me say that I use classes like this (main.cpp):
#include <iostream>
#include "Trees.h"
int main()
{
Trees Trees;
Trees.AddTree(Tree("Oak"));
Trees.AddTree(Tree("Oak"));
if(Trees.GetTree(0) == Trees.GetTree(1))
{
std::cout<<"Trees are the same" << std::endl;
if(Trees.GetTree(1).GetHasRelatives() == 1)
std::cout<<"Tree has relatives" << std::endl;
}
return 0;
}
To my current understanding, the program should output “The tree has relatives”, because the second Tree (Trees.GetTree (1)) is passed by reference, so any changes made inside the body of the == operator should be visible outside it ...
Where am I mistaken?
Cover source
share