3

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;

Source.h

#pragma once
#include <string>
class Source {
public:
    Source();
    Source(std::string namel);
    std::string getName();
};

Test.cpp

#include "Source.h"
#include "iostream"

Source first("first"), second("second");

int main()
{
    std::cout << first.getName() << std::endl;
}

Output: second

Test.h

#pragma once
#include <string>
2
  • Thanks for the example code. This clearly illustrates what you are trying to do without the details of your full program. What happens when you compile and run this code? Do you get any errors? If so, what are they? If not, what output do you get? And what do you expect instead? Commented Nov 13, 2019 at 22:23
  • You say i can't just type "Upgrade first("first"), second("second");". What is Upgrade here? And what do you expect first("first") or second("second") to do? Commented Nov 13, 2019 at 22:24

2 Answers 2

9

The problem is with this line:

std::string name;

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;
};

This will give a name for each Source. I suggest you study about class fields and the differences between public and private access.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response, it's working now!
1

add std::string name in your header file like that:

#pragma once
#include <string>
class Source {
private:
    std::string name;
public:
    Source();
    Source(std::string namel);
    std::string getName();
};

by this, everytime you call the constructor, "name" will be initiated to a single value that refers to your specific instance (first, second, etc).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.