Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I set a member of a copied class instance?

I am currently working on an instance system, so far this is something I tried:

//[...]
#include <string>
#include <list>

class Instance { // Instance class
public:
    std::string Name;
    std::string Type;
    SDL_Texture* Texture; // All this is for a list for an SDL renderer.
    int x;
    int y;
};

class instances {
public:
    Instance New(std::string Name, std::string Type) {
        Instance newInstance; // Clone the class? Doesn't raise error.
        Instance::Name = "Test"; // Set a variable from the cloned class. Error: "a nonstatic member reference must be relative to a specific object"
    };

    std::list<int> list = {}; // Ignore this...
};
//[...]

You will be able create instances with the "New" function shown above, which should return a copy of the "Instance" class (also above).

Unfortunately it raises an error as I wrote in the script comments.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that Name is a non-static data member of class Instance so you would need an object of type Instance for which you can access that field Name.

Additionally you should add a return statement inside the function New.

The correct way would be as shown below:

Instance New(std::string Name, std::string Type) {
        Instance newInstance; // create object of type Instance
//-----------------v--------------------->used . instead of ::
        newInstance.Name = "Test"; 
    
        return newInstance;//added return statement
    };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading