I am trying to understand how references work in c++ so I have make a couple files with two different objects. One is an animal and another is a zookeeper. My goal is to pass a reference of an animal to a zookeeper and have the zookeeper change the animal's name, and still be reflected in the original animal object. How is this done using references? Here are the files I'm using.
Source.cpp
#include <iostream>
#include <string>
#include "Animal.h"
#include "zookeeper.h"
using namespace std;
int main() {
Animal animal;
Animal& animalRef = animal;
printf("animal's name before it is assigned to a zookeeper: %s\n", animal.getName());
Zookeeper aZookeeper = Zookeeper(animalRef);
aZookeeper.changeMyAnimalsName("Fred");
printf("animal's name after it is assigned to a zookeeper: %s\n", animal.getName());
//Keep cmd window open
int j;
cin >> j;
return 0;
}
Animal.h
#pragma once
#include <string>
using namespace std;
class Animal {
string name = "";
int height = 0;
public:
string getName() { return name; }
int getHeight() { return height; }
void setName(string n) { name = n; }
void setHeight(int h) { height = h; }
};
zookeeper.cpp
#include "zookeeper.h"
using namespace std;
Zookeeper::Zookeeper(Animal& a) {
_myAnimal = a;
}
void Zookeeper::changeMyAnimalsName(string newName) {
_myAnimal.setName(newName);
}
zookeeper.h
#pragma once
#include "Animal.h"
class Zookeeper {
Animal _myAnimal;
public:
Zookeeper(Animal& a);
void changeMyAnimalsName(std::string newName);
};