Diego Diego - 26 days ago 7
C++ Question

Getting Member String from Class C++

I have a class that contain some game level settings.

class Stage {
private:
int level;
int stars;
std::string imgName;

public:
int getLevel(){ return level; };
void setLevel(int n){ level = n; };

int getStars(){ return stars; };
void setStars(int n){ stars = n; };

std::string getImgName(){ return imgName; };
void setImgName(std::string name){ imgName = name; };
};


Then in my program I set the info.

Stage* stagesArr = new Stage[3];

stagesArr[0].setLevel(0);
stagesArr[0].setStars(1200);
stagesArr[0].setImgName("stage0.png");


Then if I want to get this info the string is giving me an odd output.

CCLOG("Level: %i", stagesArr[0].getLevel());
CCLOG("Required stars: %i", stagesArr[0].getStars());
CCLOG("Image Name: %s", stagesArr[0].getImgName());

//Level:0
//Required stars: 1200
//Image Name: T%s //Or just random stuff.


What am I missing here?

Answer

Suspected that CCLOG() uses the same formatting rules like the <x>printf() function family does, you need to pass a const char* with the format specifier %s.

Your getImgName() returns a std::string value though, which isn't directly compatible with a const char*.

To achieve the latter, you should call the std::string::c_str() function:

 CCLOG("Image Name: %s", stagesArr[0].getImgName().c_str());

Also you can improve your getter/setter functions specifying constness applicability more clear:

   int getLevel() const { return level; }
               // ^^^^^^ 
   int getStars() const { return stars; }
               // ^^^^^^ 
   const std::string& getImgName() const { return imgName; }
// ^^^^^                       // ^^^^^^ 
void setImgName(const std::string& name) { imgName = name; }
             // ^^^^^ 

Note:
As a matter of style you can omit the get / set prefixes for getter/setter functions in c++, as the signatures are disambiguate enough:

int Level() const { return level; }
void Level(int n){ level = n; }

int Stars() const { return stars; }
void Stars(int n){ stars = n; }

const std::string& ImgName() const { return imgName; }
void ImgName(const std::string& name){ imgName = name; }

My personally preferred style is to use lower caps and disambiguate class member variables with a _ postfix:

class Stage {
private: 
    int level_;
    int stars_;
    std::string img_name_;

public:
    int level() const { return level_; }
    void level(int n) { level_ = n; }

    int stars() const { return stars_; }
    void stars(int n){ stars_ = n; }

    const std::string& img_name() const { return img_name_; }
    void img_name(const std::string& name) { img_name_ = name; };
};