My problem is that i want to create multiple instances of my upgrade class, for different upgrades. Maybe it's because i'm used to java but i can't just type Source first("first"), second("second"); because if i do and call first.getName() for example, i get "second". I made an example file where i only wrote what i'm struggling with, so you don't have to try to understand my mess of a code.
Source.cpp: I want multiple instances of this class.
#include "Source.h"
std::string name;
Source::Source()
{
}
Source::Source(std::string nameToSet)
{
name = nameToSet;
}
std::string Source::getName()
{
return name;
Run Code Online (Sandbox Code Playgroud)
Source.h
#pragma once
#include <string>
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
};
Run Code Online (Sandbox Code Playgroud)
Test.cpp
#include "Source.h"
#include "iostream"
Source first("first"), second("second");
int main()
{
std::cout << first.getName() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
Output: second
Test.h
#pragma once
#include <string>
Run Code Online (Sandbox Code Playgroud)
The problem is with this line:
std::string name;
Run Code Online (Sandbox Code Playgroud)
This declares a single global string named name. This variable is not associated with any Source instance. Instead, you need to declare a field inside the Source class:
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
// Add these two lines
private:
std::string name;
};
Run Code Online (Sandbox Code Playgroud)
This will give a name for each Source. I suggest you study about class fields and the differences between public and private access.