Getting Member String from Class C++ - 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?

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

Related

DLL Export functions that return std::string in C++

I have a namespace here with a struct and 2 functions simply for getting the date and time and computer name as part of my program. I know how to export a function, and a class but these all include other return types besides a std::string. The functions require a string to be returned because it is utilizing a stringstream, unless I can re-write it somehow. I am not an expert in C++. How would I go ahead and export this struct and these 2 functions correctly without it throwing errors? Thanks
namespace Helper
{
std::string getName();
template <class T>
std::string ToString(const T &);
struct DateTime
{
DateTime()
{
time_t ms;
time(&ms);
struct tm * info = localtime(&ms);
D= info->tm_mday;
m = info->tm_mon+1;
y= 1900 + info->tm_year;
M=info->tm_min;
H=info->tm_hour;
S= info->tm_sec;
}
DateTime(int D,int m,int y,int H,int M,int S):
D(D), m(m),y(y),
H(H),M(M),S(S)
{
}
DateTime(int D,int m,int y):
D(D), m(m),y(y),
H(0),M(0),S(0)
{
}
DateTime Now()const
{
return DateTime();
}
int D,m,y,H,M,S;
std::string GetDateString()const
{
return std::string(D <10 ? "0":"") +ToString(D)+
std::string(m<10 ? ".0":".")+ ToString(m)+ "."+
ToString(y);
}
std::string GetTimeString(const std::string &sep=":")const
{
return std::string(H<10 ? "0":"")+ToString(H)+ sep+
std::string(M<10 ? "0":"")+ToString(M)+ sep+
std::string(S<10 ? "0":"")+ToString(S);
}
std::string GetDateTimeString(const std::string &sep=":")const
{
return GetDateString()+"__"+GetTimeString(sep);
}
};
template <class T>
std::string ToString(const T &e)
{
std::ostringstream s;
s << e;
return s.str();
}
std::string getName()
{
char buffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD length = sizeof(buffer);
int i;
bool ok = GetComputerNameExA((COMPUTER_NAME_FORMAT)0, buffer, &length);
i = strlen(buffer);
buffer[i] = '_';
buffer[++i] = '_';
buffer[++i] = '\0';
return buffer;
}
}

C++ OOP Abstract Class - Access violation writing location

I have an UserAcount class that has an abstract class ContBancar, and other class Banca which reads some users from a file (with method void Banca::citire_conturi()). When it reads the users, I get an error "Access violation writing location" in ContBancar at void setBal(double bal) { _balanta = bal; }. Thx for help !
PS : The file has only one line : 1CBS Dragos 0 dragos12! Gzpvia01= .
Also, i want to make a bank account system, with an user class that has an bank account class which inherits 3 types of a bank accounts, and a bank class which reads some users from a file or put them on it.
class UserAccount
{
private:
std::string _nume, _user, _pass;
std::string _cod_us;
std::shared_ptr <ContBancar> _cont;
public:
void setUser(std::string user) { _user = user; }
void setPass(std::string pass) { _pass = pass; }
void setNume(std::string nume) { _nume = nume; }
void setCodUs(std::string cod) { _cod_us = cod; }
void setContBal(double balanta) { (*_cont).setBal(balanta); }
std::string getUser() const { return _user; }
std::string getPass() const { return _pass; }
std::string getNume() const { return _nume; }
std::string getCodUs() const { return _cod_us; }
double getContBal() const { return (*_cont).getBal(); }
void setContBancar();
};
void UserAccount::setContBancar()
{
if (_cod_us == "1CBS")
_cont.reset(new ContBancarSilver());
else if (_cod_us == "2CBG")
_cont.reset(new ContBancarGold());
else
_cont.reset(new ContBancarDiamond());
}
class ContBancar
{
protected:
double _balanta;
public:
void setBal(double bal) { _balanta = bal; }
double getBal() { return _balanta; }
virtual bool depozitare(unsigned int) = 0;
virtual bool retragere(unsigned int) = 0;
};
class Banca
{
private:
std::vector<UserAccount> vec;
public:
void citire_conturi();
};
void Banca::citire_conturi()
{
std::ifstream file;
file.open("Baza_Date.txt");
UserAccount temp;
std::string cod, nume, user, pass;
double balanta;
while (file >> cod >> nume >> balanta >> user >> pass)
{
temp.setCodUs(cod);
temp.setNume(nume);
temp.setContBal(balanta);
temp.setUser(user);
temp.setPass(pass);
vec.push_back(temp);
}
file.close();
}
class ContBancarSilver : public ContBancar
{
private:
static constexpr unsigned int max_balanta = 5000;
static constexpr unsigned int max_depozitare = 2500;
static constexpr unsigned int max_retragere = 1000;
static constexpr double tax_retragere = 0.08;
static constexpr double bonus_depunere = 0.03;
static constexpr double bonus_tax_retragere = 0.05;
static constexpr unsigned int max_depozitari = 1;
static constexpr unsigned int max_retrageri = 1;
public:
virtual bool depozitare(unsigned int) override;
virtual bool retragere(unsigned int) override;
};
Based on available informationyou should fix your code like this:
class UserAccount
{
.....
void setCodUs(std::string cod) {
_cod_us = cod;
setContBancar();
}
void setContBal(double balanta) {
if (!_cont) setContBancar(); // lazy initialization
_cont->setBal(balanta);
}
...
};
void UserAccount::setContBancar()
{
if (_cod_us == "1CBS")
_cont = std::make_shared<ContBancarSilver>();
else if (_cod_us == "2CBG")
_cont = std::make_shared<ContBancarGold>();
else
_cont = std::make_shared<ContBancarDiamond>();
}
Note I do not understand what kind of logic you are implementing. This changes just ensured that _cont is initialized and up to date with _cod_us.
Please stop use explicitly new and delete. Everything can be created by std::make_shared and std::make_unique and containers like std::vector.

Class does not persist vector of objects after addition

My code is as shown below. The problem is inside the int main() function, r.printItems() is not printing anything. What am I missing here?
main.cpp
#include <bits/stdc++.h>
#include "Customer.h"
#include "MenuCreator.h"
#include "FoodItem.h"
MenuCreator m1;
void createCustomer() {
Customer c1("mrg", "m#gmail.com", "9654357", "+91");
}
void createRestaurantItem(Restaurant &rest) {
rest.addItems(FoodItem("t1"));
rest.addItems(FoodItem("D1"));
}
void createMenu() {
m1.createMenu("sg");
Category c1;
c1.setName("Non-veg");
m1.addCategory(c1);
Restaurant r1;
r1.setName("ABC");
r1.setDescription("Test Restaurant");
createRestaurantItem(r1);
c1.addRestaurants(r1);
}
vector<Restaurant> getRestaurantsForCategory(string category) {
return m1.getRestaurantsForCategories(category);
}
int main() {
createCustomer();
createMenu();
for (auto r: getRestaurantsForCategory("Non-veg")) {
r.printItems();
}
return 0;
}
MenuCreator.h
#include <bits/stdc++.h>
#include "Menu.h"
using namespace std;
class MenuCreator {
public:
void createMenu(string name) {
Menu m1;
m1.setName(name);
menu = m1;
}
void addCategory(const Category &categ) {
categories.push_back(categ);
}
const Menu &getMenu() const {
return menu;
}
const vector<Category> &getCategories() const {
return categories;
}
void addRestaurantForCategory(string name, const Restaurant restaurant) {
for(auto categ: categories) {
if (categ.getName() == name) {
categ.addRestaurants(restaurant);
}
}
}
const vector<Restaurant> &getRestaurantsForCategories(string category) {
for(auto categ: categories) {
if(categ.getName() == category) return categ.getRestaurants();
}
}
private:
Menu menu;
vector<Category> categories;
};
Menu.h
#include<bits/stdc++.h>
#include "Category.h"
using namespace std;
class Menu {
public:
const string &getName() const {
return name;
}
void setName(const string &name) {
Menu::name = name;
}
private:
string name;
string description;
vector<Category> categories;
};
Category.h
using namespace std;
class Category {
public:
const string &getName() const {
return name;
}
void setName(const string &name) {
Category::name = name;
}
const string &getDescription() const {
return description;
}
void setDescription(const string &description) {
Category::description = description;
}
const vector<Restaurant> &getRestaurants() const {
return restaurants;
}
void setRestaurants(const vector<Restaurant> &restaurants) {
Category::restaurants = restaurants;
}
void addRestaurants(const Restaurant &rt) {
Category::restaurants.push_back(rt);
}
private:
string name;
string description;
vector<Restaurant> restaurants;
};
FoodItem.h
#include <bits/stdc++.h>
#include <vector>
#include "FoodItem.h"
using namespace std;
class Restaurant {
public:
Restaurant() {
this->id = gen_random(12);
}
virtual ~Restaurant() {
}
const string &getName() const {
return name;
}
void setName(const string &name) {
Restaurant::name = name;
}
const string &getDescription() const {
return description;
}
void setDescription(const string &description) {
Restaurant::description = description;
}
double getLat() const {
return lat;
}
void setLat(double lat) {
Restaurant::lat = lat;
}
double getLang() const {
return lang;
}
void setLang(double lang) {
Restaurant::lang = lang;
}
const string &getImageUrl() const {
return imageUrl;
}
void setImageUrl(const string &imageUrl) {
Restaurant::imageUrl = imageUrl;
}
const string &getVideoUrl() const {
return videoUrl;
}
void setVideoUrl(const string &videoUrl) {
Restaurant::videoUrl = videoUrl;
}
const vector<FoodItem> &getItems() const {
return items;
}
void setItems(const vector<FoodItem> &items) {
Restaurant::items = items;
}
void addItems(const FoodItem &item) {
this->items.push_back(item);
}
string gen_random(const int len) {
string tmp_s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid());
tmp_s.reserve(len);
for (int i = 0; i < len; ++i)
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s;
}
const string &getId() const {
return id;
}
void printItems() {
for(auto it: items) {
cout<<"item: "<<it.getName()<<endl;
}
}
private:
string id;
string name;
string description;
double lat;
double lang;
string imageUrl;
string videoUrl;
string createdAt;
string updatedAt;
vector<FoodItem> items;
};
Restaurant.h
#include <bits/stdc++.h>
#include <vector>
#include "FoodItem.h"
using namespace std;
class Restaurant {
public:
Restaurant() {
this->id = gen_random(12);
}
virtual ~Restaurant() {
}
const string &getName() const {
return name;
}
void setName(const string &name) {
Restaurant::name = name;
}
const string &getDescription() const {
return description;
}
void setDescription(const string &description) {
Restaurant::description = description;
}
double getLat() const {
return lat;
}
void setLat(double lat) {
Restaurant::lat = lat;
}
double getLang() const {
return lang;
}
void setLang(double lang) {
Restaurant::lang = lang;
}
const string &getImageUrl() const {
return imageUrl;
}
void setImageUrl(const string &imageUrl) {
Restaurant::imageUrl = imageUrl;
}
const string &getVideoUrl() const {
return videoUrl;
}
void setVideoUrl(const string &videoUrl) {
Restaurant::videoUrl = videoUrl;
}
const vector<FoodItem> &getItems() const {
return items;
}
void setItems(const vector<FoodItem> &items) {
Restaurant::items = items;
}
void addItems(const FoodItem &item) {
this->items.push_back(item);
}
string gen_random(const int len) {
string tmp_s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid());
tmp_s.reserve(len);
for (int i = 0; i < len; ++i)
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s;
}
const string &getId() const {
return id;
}
void printItems() {
for(auto it: items) {
cout<<"item: "<<it.getName()<<endl;
}
}
private:
string id;
string name;
string description;
double lat;
double lang;
string imageUrl;
string videoUrl;
string createdAt;
string updatedAt;
vector<FoodItem> items;
};
When createMenu() in main.cpp is setting up the menu, it creates a local Category object named c1 and adds it to the menu, which makes a copy of c1 when pushingnit into the MenuCreator::categories vector. No Restaurant objects had been added to c1 yet when that copy is created. So when a Restaurant is then added to c1 afterwards, the copy is not updated. That is why there are no Restaurant objects in the menu when MenuCreator::getRestaurantsForCategory() tries to return them.
Change createMenu() to fully initialize c1 before adding it to the menu, eg:
void createMenu() {
m1.createMenu("sg");
Category c1;
c1.setName("Non-veg");
Restaurant r1;
r1.setName("ABC");
r1.setDescription("Test Restaurant");
createRestaurantItem(r1);
c1.addRestaurants(r1);
m1.addCategory(c1); // <-- move down here
}
Also, on a side note, the return value of MenuCreator::getRestaurantsForCategories() is undefined if the specified category is not found. Since the return value is a reference to a vector, it needs to either return a static vector that is empty, or else throw an exception.

Passing c-strings to class function (assigning it to class member)

I have a class called Person:
class Person {
private:
char name[50];
unsigned int number;
public:
void set_data(const char *newname, unsigned int number) {
*name= *newname; //THE MAIN PROBLEM I WANT TO SOLVE
this->number = number;
}
char* get_name() {
return this->name;
}
unsigned int get_number() {
return this->number;
}
};
I have arrays:
const char *names[] = {"Mark", "Pavel", "Bill", "Jasur", "Jeff"};
int phones[] = { 1234567890, 9876543210, 123321456654, 1998946848479, 1234554321 };
I'm using for loop to set Person members:
Person p;
for (int i = 0; i < 5; i++) {
p.set_data(names[i], phones[i]);
cout << p.get_name() << endl;
}
When I run this, I'm getting wrong output.
Using * the way you are, you are only copying the 1st char into name. You are also not null-terminating name either, which is required by the overloaded operator<< that takes a char* as input.
To copy the entire string, you need to use std::strcpy() (or better, std::strncpy()) instead, eg:
#include <cstring>
void set_data(const char *newname, unsigned int newnumber) {
//std::strcpy(name, newname);
std::strncpy(name, newname, 49);
name[49] = '\0';
number = newnumber;
}
However, since this is C++ and not C, you really should be using std::string instead:
#include <string>
class Person {
private:
std::string name;
unsigned int number;
public:
void set_data(const std::string &newname, unsigned int newnumber) {
name = newname;
number = newnumber;
}
std::string get_name() const {
return name;
}
/* or:
const std::string& get_name() const {
return name;
}
*/
unsigned int get_number() const {
return number;
}
};

0xC0000005: Access violation writing location 0xCCCCCCCC caused by trying to make safe empty chars

I've been pulling my hair out over a certain error that seems to be plaguing my program. I've attempted to search online for cases similar to mine but I can't seem to find a way to apply the other solutions to this problem. My issue is as follows: When I initially open the program it immediately stops responding and crashes. Debugging led me to find the error in question is "0xC0000005: Access violation writing location 0xCCCCCCCC". It seems to be tied to me assigning two attributes (sku_ and name_ ) as '\0'. If I change these values to anything else such as "" or even "\0" the program runs in visual studio, but will fail to compile elsewhere. Could someone help me understand where I am going wrong?
Product.h
#ifndef SICT_Product_H__
#define SICT_Product_H__
#include "general.h"
#include "Streamable.h"
#include <cstring>
namespace sict {
class Product : public Streamable {
char sku_ [MAX_SKU_LEN + 1];
char* name_;
double price_;
bool taxed_;
int quantity_;
int qtyNeeded_;
public:
//Constructors
Product();
Product(const char* sku, const char* name1, bool taxed = true, double price = 0, int qtyNeeded =0);
Product(Product& g);
~Product();
//Putter Functions
void sku(const char* sku) { strcpy(sku_,sku); };
void price(double price) {price_ = price;};
void name(const char* name);
void taxed(bool taxed) { taxed_ = taxed; };
void quantity(int quantity) { quantity_ = quantity; };
void qtyNeeded(int qtyNeeded) { qtyNeeded_ = qtyNeeded; };
//Getter functions
const char* sku() const { return sku_; };
double price() const { return price_; };
const char* name() const { return name_; };
bool taxed() const { return taxed_; };
int quantity() const { return quantity_; };
int qtyNeeded() const { return qtyNeeded_; };
double cost() const;
bool isEmpty() const;
Product& operator=(const Product& );
bool operator==(const char* );
int operator+=(int );
int operator-=(int );
};
double operator+=(double& , const Product& );
std::ostream& operator<<(std::ostream& os, const Product& );
std::istream& operator>>(std::istream& is, Product& );
}
#endif
Product.cpp
#include <iostream>
#include <cstring>
#include "Product.h"
namespace sict {
Product::Product() {
sku_[0] = '\0';
name_[0] = '\0';
price_ = 0;
quantity_ = 0;
qtyNeeded_ = 0;
}
Product::Product(const char* sku, const char* name1, bool taxed1, double price1, int qtyNeeded1) {
strncpy(sku_, sku, MAX_SKU_LEN);
name(name1);
quantity_ = 0;
taxed(taxed1);
price(price1);
qtyNeeded(qtyNeeded1);
}
double Product::cost() const {
if (taxed_ == true) {
return (price_ * TAX) + price_;
}
else
return price_;
}
bool Product::isEmpty() const{
if (sku_ == nullptr && name_ == nullptr && quantity_ == 0 && price_ == 0 && qtyNeeded_ == 0) {
return true;
}
else
return false;
}
Product::Product(Product& ex) {
sku(ex.sku_);
price(ex.price_);
name(ex.name_);
taxed(ex.taxed_);
quantity(ex.quantity_);
qtyNeeded(ex.qtyNeeded_);
}
Product& Product::operator=(const Product& g) {
sku(g.sku_);
price(g.price_);
name(g.name_);
taxed(g.taxed_);
quantity(g.quantity_);
qtyNeeded(g.qtyNeeded_);
return *this;
}
Product::~Product() {
delete [] name_;
}
void Product::name(const char* name) {
name_ = new char [strlen(name) + 1];
strcpy(name_, name);
}
bool Product::operator==(const char* right) {
if (sku_ == right) {
return true;
}
else
return false;
}
int Product::operator+=(int g) {
quantity_ = quantity_ + g;
return quantity_;
}
int Product::operator-=(int g) {
quantity_ = quantity_ - g;
return quantity_;
}
double operator+=(double& p, const Product& right) {
p = p + (right.cost() * right.quantity());
return p;
}
std::ostream& operator<<(std::ostream& os, const Product& g) {
return g.write(os, true);
}
std::istream& operator>>(std::istream& is, Product& g) {
return g.read(is);
}
}
The General.h file referenced in the header is just a list of constant values such as the "TAX" and "MAX_SKU_LEN" values.
The Streamable header contains pure virtual functions. I will list it here in case it is needed.
Streamable.h
#ifndef SICT__Streamable_H_
#define SICT__Streamable_H_
#include <iostream>
#include <fstream>
#include "Product.h"
namespace sict {
class Streamable {
public:
virtual std::fstream& store(std::fstream& file, bool addNewLine = true)const = 0;
virtual std::fstream& load(std::fstream& file) = 0;
virtual std::ostream& write(std::ostream& os, bool linear)const = 0;
virtual std::istream& read(std::istream& is) = 0;
};
}
#endif
Thank you very much in advance.
Product::Product() {
sku_[0] = '\0';
name_[0] = '\0'; // <---- writing via unitialized pointer
price_ = 0;
quantity_ = 0;
qtyNeeded_ = 0;
}
There's one possible source of your problems. You have defined a char pointer (a dynamic array or a C-string, that is) name_ in your class but you never allocate any memory for it in your constructor, before attempting to record a value via the pointer. Naturally, you get a write access violation.
Before assigning the value to char at index [0] you need to first allocate space for at least one element in your string, e.g. by doing name_ = new char [1]. Alternatively, you may choose to initialize the pointer itself to NULL (or nullptr) and use that to indicate that name_ has not yet been set.