C++ set and get method not producing values? - c++

i have these set and get methods declared in my main cpp file
void issuesofRelevance::setApproach(int Approach) {
approach = Approach;
}
int issuesofRelevance::getApproach() {
return approach;
}
void issuesofRelevance::setSignifiance(int Significance) {
significance = Significance;
}
int issuesofRelevance::getSignificance() {
return significance;
}
The following H file is attatched in which I call the setMethods in its constructor.
class issuesofRelevance
{
public:
std::vector<std::string> issueName;
int significance;
int approach;
std::vector<std::string> newList;
issuesofRelevance(std::vector<std::string> issueName, int significance, int approach){
issueName = issueName;
significance = significance;
approach = approach;
setApproach(15);
setSignifiance(15);
}
issuesofRelevance();
void setIssues();
std::string getIssues();
void setApproach(int x);
void setSignifiance(int);
int getApproach();
int getSignificance();
};
I call the get functions in main int() as such
cout << object.getApproach();
cout << object.getSignificance();
However, when i go to run the code in the console I get no output when it should return the values of 10 and 15. Im unsure as to why this is occuring
Thankyou.
my full main as requested
int main(int argc, char* argv[]) { //takes in n, number of electorates, and m, the number of campagian days
issuesofRelevance newIssues(newIssues.issueName, newIssues.significance, newIssues.approach);
return 0;
Party party;
Person person;
Electrorates electorate;
string numberofElectoratesAsString = argv[1]; //number of electorates taking as a argument
string DaysOfElectionAsString = argv[2]; //takes in argument 2
int numberofElectorates = std::stoi(numberofElectoratesAsString);
int DaysOfElection = std::stoi(DaysOfElectionAsString );
cout << "Number of electorates: " << electorate.assignID(electorate.numberofElectorates(numberofElectorates));
cout << "Stance: " << person.setinitalStance(numberofElectorates, DaysOfElection) << endl;
newIssues.setIssues();
cout<<newIssues.getApproach()<< " "<<newIssues.getSignificance();
return 0;
}
default constructor
issuesofRelevance::issuesofRelevance(){
}

Related

How do I get a for loop to work while searching a vector for objects that share elements with another vector in C++?

I've got a C++ program with two input files and an output file. The first input file has a list of products (subclass stock), and the second input file has a list of orders. I've worked out how to deal with most of the problems that I've had, and I've gotten so close, but I need to read the items in the arrOrders vector, and compare them with the orderTitle and stockLevel in the arrStock vector. I've managed to get it to work for the first item in the order list, but I can't get it to work beyond there.
class Product {
public:
std::string title, surname;
long long int isbn;
double wholesalePrice;
void setProductInfo(std::string, std::string, long long int, double);
void setTitle(std::string);
void setSurname(std::string);
void setWholesalePrice(double);
void setIsbn(long long int);
double getWholesalePrice();
long long int getIsbn();
std::string getTitle();
std::string getSurname();
Product();
~Product();
Product(std::string, std::string, long long int, double);
};
class Stock :public Product
{
public:
double retailPrice;
char bookFormat;
int stockLevel;
std::string calcRP;
Stock(std::string, int, char, std::string, double, long long int, double);
Stock();
~Stock();
double getRetailPrice();
char getBookFormat();
int getStockLevel();
void setStockLevel(int);
void setBookFormat(char);
void setRetailPrice(double);
};
class Order {
public:
std::string orderTitle;
int orderStock;
Order(std::string, int);
Order();
~Order();
void setStock(int);
void setTitle(std::string);
std::string getTitle();
int getStock();
};
void importBooks();
void runReport();
void newBook();
void delBook();
std::vector<Stock> arrStock{};
std::vector<Order> arrOrders{};
void checkStock();
//lots of code
//checkStock function
void checkStock()
{
std::ifstream inFile("orders_v5.txt");
Order anOrder;
std::string orderTitle;
int orderStock;
inFile >> anOrder.orderTitle >> anOrder.orderStock;
arrOrders.push_back(anOrder);
std::cout << "#########################################################################################"; std::cout << std::endl;
std::cout << " ORDER REPORT"; std::cout << std::endl;
std::cout << "#########################################################################################"; std::cout << std::endl;
// code adapted from https://en.cppreference.com/w/cpp/algorithm/find
for (unsigned int k = 0; k < arrOrders.size(); k++)
{
orderTitle = arrOrders[k].getTitle();
orderStock = arrOrders[k].getStock();
std::vector<Stock>:: iterator test1 = find_if(arrStock.begin(), arrStock.end(), [&orderTitle](const Stock stock)->bool
{
for (unsigned int m = 0; m < arrStock.size(); m++)
{
return stock.title == orderTitle;
}
});
std::vector<Stock>::iterator test2 = find_if(arrStock.begin(), arrStock.end(), [&orderStock](const Stock stock)->bool
{
for (unsigned int m = 0; m < arrStock.size(); m++)
{
return arrStock[m].getStockLevel() >= orderStock;
}
});
if (test1 != arrStock.end())
{
if (test2 != arrStock.end())
{
std::cout << orderTitle << " is available at Biblioden and there is enough stock to fulfil your older.";
}
else
{
std::cout << orderTitle << " is available at Biblioden but there is not enough stock to fulfil your order.";
}
}
else
{
std::cout << orderTitle << " is not available at Biblioden.";
}
}
}

Why the number of grades is 0?

#include<iostream>
#include<string>
using namespace std;
class Student {
public:
const int codeStud;
int noGrades = 0;
int* grades = NULL;
Student(int code) :codeStud(code) {
}
Student(int code, int* grades, int noGrades) :codeStud(code) {
this->noGrades = noGrades;
this->grades = new int[noGrades];
for (int i = 0; i < noGrades; i++)
this->grades[i] = grades[i];
}
Student(const Student&existent):codeStud(existent.codeStud) {
this->noGrades = existent.noGrades;
this->grades = new int[this->noGrades];
for (int i = 0; i < this->noGrades; i++)
this->grades[i] = existent.grades[i];
}
int getCode() {
return this->codeStud;
}
int getNoGrades() {
return this->noGrades;
}
void setGrades(int grades[],int noGrades) {
this->noGrades = noGrades;
this->grades = new int[noGrades];
for (int i = 0; i < noGrades; i++)
this->grades[i] = grades[i];
}
};
void main() {
Student s1(101);
cout<<s1.getNoGrades();
int grades[] = { 10,7,8,10,4 };
Student s2(104, grades, 5);
cout << "\n" << s2.getNoGrades();
Student s3 = s2;
cout << "\n" << s3.getCode();
int grades2[] = { 5,5,4,10 };
s1.setGrades(grades2,4);
cout << "\n" << s1.getNoGrades(); // here is the problem
}
After I changed the grades for student 1 it shows that he has 0 grades, when the output should be 4, the number of these grades: 5,5,4,10.
The rest of output is correct, even when I want to know the number of grades for student 1, which is 0 , and then for student 2, which is 5.
I've changed some things in your code to compile it
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
int codeStud;
int noGrades = 0;
int* grades = NULL;
Student(int code) {
codeStud = code;
}
Student(int code, int* grades, int noGrades) {
this->noGrades = noGrades;
this->grades = new int[noGrades];
for (int i = 0; i < noGrades; i++)
this->grades[i] = grades[i];
}
Student(const Student&existent){
this->noGrades = existent.noGrades;
this->grades = new int[this->noGrades];
for (int i = 0; i < this->noGrades; i++)
this->grades[i] = existent.grades[i];
}
int getCode() {
return this->codeStud;
}
int getNoGrades() {
return this->noGrades;
}
void setGrades(int grades[],int noGrades) {
this->noGrades = noGrades;
this->grades = new int[noGrades];
for (int i = 0; i < noGrades; i++)
this->grades[i] = grades[i];
}
};
int main() {
Student s1(101);
cout<<s1.getNoGrades();
int grades[] = { 10,7,8,10,4 };
Student s2(104, grades, 5);
cout << "\n" << s2.getNoGrades();
Student s3 = s2;
int grades2[] = { 5,5,4,10 };
s1.setGrades(grades2,4);
cout << "\n" << s1.getNoGrades(); // here is the problem
}
and output is:
0
5
4
what is correct, because you don't assign number of grades of s1 anywhere in your code before first printing
Also look for:
https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c
why void main() is not correct
After I corrected the typo (codStud --> codeStud) your code produced the correct results for me. Before I did that I couldn't even compile it, so my guess would be that your IDE just run the latest working version of it that could be compiled successfully (look for error messages somewhere). That's the reason you got the wrong result, because your changes weren't even in that version.
A couple of note about your code:
In your setGrades function check that grades not pointing to something already. For example, if I call Student(int code, int* grades, int noGrades) and after I call setGrades your code leaks memory because it loses the array that Student(int code, int* grades, int noGrades) allocated before.
You should use vector instead of C-style arrays. It will make your code much more cleaner and less error-prone (see my example).
You could make your getter functions to const (like in my example), so it would be guaranteed that those functions don't change the value of any member of the class (you get a compile error if they do). Other than that, you can make the member variables to private.
Implementation using vectors:
#include <iostream> // cout
#include <vector> // vector
using namespace std;
class Student
{
public:
Student(const int code)
: m_code{code}
{
}
Student(const int code, const std::vector<int>& grades)
: m_code{code},
m_grades{grades}
{
}
// Default copy constructor is sufficient because the class can be copied
// memberwise.
int getCode() const {
return m_code;
}
int getNoGrades() const {
return m_grades.size();
}
void setGrades(const std::vector<int>& grades) {
m_grades = grades;
}
private:
const int m_code;
std::vector<int> m_grades;
};
int main()
{
Student s1(101);
cout << s1.getNoGrades();
Student s2(104, {10, 7, 8, 10, 4});
cout << "\n" << s2.getNoGrades();
Student s3 = s2;
cout << "\n" << s3.getCode();
s1.setGrades({5, 5, 4, 10});
cout << "\n" << s1.getNoGrades();
return 0;
}

Getting warning "deprecated conversion from string constant to char*. Why am I getting the warnings?

I am a beginner in C++. I am working on inheritance. I have written a code and compiled it and it seems to be working fine and I am getting the expected output. But when I compile it, I get 13 similar warnings. I am not sure what is the problem? How can I override these warnings? Here is my code:
#include <iostream>
#include <string.h>
using namespace std;
class Identity
{
protected:
char *name;
int dob;
char* blood_group;
Identity(char *iname="", int nlength=1, int idob=0, char *iblood_group="", int blength=2):dob(idob)
{
name = new char[nlength+1];
strncpy(name,iname,nlength);
name[nlength]='\0';
blood_group = new char[blength+1];
strncpy(blood_group,iblood_group,blength);
blood_group[blength]='\0';
}
~Identity()
{
delete[] name;
delete[] blood_group;
}
};
class Physical
{
protected:
double height;
double weight;
Physical(double pheight = 0.0, double pweight = 0.0):height(pheight),weight(pweight)
{
}
};
class Registration
{
protected:
int policy_number;
char* contact_address;
Registration(int p_num=0, char* addr="", int alength=1):policy_number(p_num)
{
contact_address = new char[alength+1];
strncpy(contact_address,addr,alength);
contact_address[alength] = '\0';
}
~Registration()
{
delete[] contact_address;
}
};
class Contact:public Identity, public Physical, public Registration
{
private:
char* ph_number;
char* driver_license;
public:
Contact(char *name ="",int nlength=0,int dob = 0, char* blood = "", int blength = 0,double height = 0, double weight = 0, int pol_num = 0, char* cont_addr="", int alength=10, char *ph="",int plength=10,char* lic="",int llength=10):Identity(name,nlength,dob,blood,blength),Physical(height,weight), Registration(pol_num,cont_addr,alength), ph_number(ph),driver_license(lic)
{
ph_number = new char[plength+1];
strncpy(ph_number,ph,plength);
ph_number[plength] = '\0';
driver_license = new char[llength+1];
strncpy(driver_license,lic,llength);
driver_license[llength] = '\0';
}
~Contact()
{
delete[] ph_number;
delete[] driver_license;
}
char* GetName()
{
return name;
}
int GetDob()
{
return dob;
}
char* GetBloodGroup()
{
return blood_group;
}
double GetHeight()
{
return height;
}
double GetWeight()
{
return weight;
}
int GetPolicyNum()
{
return policy_number;
}
char* GetAddress()
{
return contact_address;
}
char* GetPhoneNumber()
{
return ph_number;
}
char* GetDriverLicense()
{
return driver_license;
}
};
int main()
{
using namespace std;
Contact kck("MyName",strlen("MyName"),11111111,"A+",strlen("A+"),15.10,651.5,1111,"MyArea",strlen("MyArea"),"1111111111", strlen("1111111111"),"ABCD1234",strlen("ABCD1234"));
cout << kck.GetName() << endl;
cout << kck.GetDob() << endl;
cout << kck.GetBloodGroup() << endl;
cout << kck.GetHeight() << endl;
cout << kck.GetWeight() << endl;
cout << kck.GetPolicyNum() << endl;
cout << kck.GetAddress() << endl;
cout << kck.GetPhoneNumber() << endl;
cout << kck.GetDriverLicense() << endl;
return 0;
}
In many places you write things like:
char *name = ""
However, "" has type const char[1] . This implicitly converts to const char *. But then you try to assign it to a char *, which is an attempt to ignore the const qualifier.
Since C++11 this is not allowed at all. Before C++11 this was allowed but deprecated. The compiler is warning you that it's a bad idea.
If you really must use pointers, then use char const * for any situation where you might be pointing to a string literal.
But you would be far better off avoiding the use of pointers entirely, as they complicate your code and introduce the opportunity for errors where there would be none if you hadn't used pointers. Passing the length of your strings separately from the string is extremely bad.
For example, use string to hold all of your strings. As a beginner, it would be good to begin with the easiest technique, which coincidentally is also the best technique. The way you have written your program so far is just making life difficult for yourself for no reason.

C++ Array passig parameters

I'm new in C++
I try to pass array as parameters I can't find a solution.
Here's my code :
My Header code
autobus.h
#ifndef autobus_H
#define autobus_H
#include <iostream>
using namespace std;
class autobus{
public :
int placeautobus[2] [40];
autobus();
void affichageTicket();
int calculdesplaces(int, int);
};
#endif
Bus.cpp
#include <iostream>
#include "autobus.h"
autobus::autobus(){
int i,j;
for (i=0;i<2;i++) {
for (j=0;j<40;j++)
placeautobus[i][j] = 0;
}
};
void autobus::affichageTicket()
{
}
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){
int placenumero;
for (int place = 0; place < 40; place++){
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "autobus.h"
using namespace std;
int main()
{
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
system("PAUSE");
return EXIT_SUCCESS;
}
Everything works, but when I add this line in my main.cpp :
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
I have an error, I try many things.
I just want to call my function calculdesplaces with the variable : choixautobus having array placeautobus.
Can someone know how to do this.
thanks
Like others have said already, the code you have now shouldn't compile right now because of the declaration and definition mismatch for calculdesplaces.
You shouldn't need to pass the placeautobus array at all since it is a member of the autobus class. Just delete your 2nd argument from calculdesplaces and you should be able to do what you want.
int autobus::calculdesplaces(int typeautobus){
int placenumero;
for (int place = 0; place < 40; place++){
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
In your class declaration, you need to specify the correct array pointer type for the second parameter of calculdesplaces():
class autobus{
public :
autobus();
void affichageTicket();
int calculdesplaces(int typeautobus, int (*placeautobus)[40]);
int placeautobus[2][40];
};
This declares, that you are passing a pointer to an array of 40 int elements. This is precisely the type to which the 2D array int placeautobus[2][40]; decays when you use its name: When you mention the name of an array, the array name decays into a pointer to its first element. In the case of an array of type int ()[2][40], that is a pointer to the first line array (type is int (*)[40]).
Note that the parentheses in int (*placeautobus)[40] are very important: the array subscript operator [] has a higher precedence than the dereferencing operator *, so int (*placeautobus)[40] means something very different from int* placeautobus[40].
I have also taken the liberty of including the variable names in the method declaration, this provides essential information to the reader, even though the compiler ignores it.
In the implementation of calculdesplaces(), you can access the argument array precisely the same way as you can access any 2D array:
int autobus::calculdesplaces(int typeautobus, int (*placeautobus)[40]) {
int placenumero;
for (int place = 0; place < 40; place++) {
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
Now you can easily call your function by just passing the array:
int main() {
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus);
system("PAUSE");
return EXIT_SUCCESS;
}
Note:
The above only fixes the symptoms, not the disease. The actual problem is, that the design of the class itself is flawed. Data members should generally not be public, and methods should work on the data of the object on which they are called, instead of relying on getting parts of the object passed in via additional arguments. So, the class definition should look like this:
class autobus{
public :
autobus();
void affichageTicket();
int calculdesplaces(int typeautobus);
private:
int placeautobus[2][40];
};
The definition of calculdesplaces() doesn't change that much, it just does not shadow the already available array member with a function argument:
int autobus::calculdesplaces(int typeautobus) {
int placenumero;
for (int place = 0; place < 40; place++) {
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
And you don't need to "grab into the object" in main(), the array is implicitly passed via the this pointer:
int main() {
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus);
system("PAUSE");
return EXIT_SUCCESS;
}
You haven't mentioned what the error it. But I think this it the issue:
What is the data type of second argument in calculdesplaces function declaration:
int calculdesplaces(int, int);
It is: int
What is the data type of placeautobus[2][40] in calculdesplaces function definition:
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){ ... }
It is: int*
What is the data type of placeautobus[2][40] in calculdesplaces function call:
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
Looking at class autobus { ... }, it is: int
So there is mismatch between the datatype used in function declaration, definition and call. Try solving this.
The code should not be compiled.
The member function declaration of calculdesplaces
int calculdesplaces(int, int);
does not coinside with its definition
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){
The type of the second parameter differs.
As for the error message then the function should be called as
choixautobus->calculdesplaces( TypeAutobus, choixautobus->placeautobus );
Take into account that the function has a bug. You pass to the function as the first argument either 1 or 2 and use these values as indices of the array while the valid indices are 0 and 1.
Also the function does not need to have the second parameter because it deals with the data member
int placeautobus[2] [40];
So I would define the class and member functions the following way
class autobus{
public :
int placeautobus[2] [40];
autobus();
void affichageTicket();
int calculdesplaces(int);
};
#include <iostream>
#include "autobus.h"
autobus::autobus() : placeautobus {}
{
}
void autobus::affichageTicket()
{
}
int autobus::calculdesplaces( int typeautobus )
{
int placenumero = 0;
for (int place = 0; place < 40; place++)
{
if ( placeautobus[typeautobus - 1][place] == 0 )
{
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
break;
}
}
return placenumero;
}
Though I do not understand what you return from the function.:)
Also you could specify the initialization of the array inside the class definition
class autobus{
public :
int placeautobus[2] [40] = {};
//...
In this case the main can look as
int main()
{
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces( TypeAutobus );
system("PAUSE");
return EXIT_SUCCESS;
}

cyclic negative number generation in C++

I have requirement as follows.
I have to generate increment negative numbers from -1 to -100 which is used a unique id for a request. Like it should be like this: -1, -2, -3, ...-100, -1, -2, and so on. How can I do this effectively? I am not supposed to use Boost. C++ STL is fine. I prefer to write simple function like int GetNextID() and it should generate ID. Request sample program on how to do this effectively?
Thanks for your time and help
int ID = -1;
auto getnext = [=] mutable {
if (ID == -100) ID = -1;
return ID--;
};
Fairly basic stuff here, really. If you have to ask somebody on the Interwebs to write this program for you, you should really consider finding some educational material in C++.
I love the functor solution:
template <int limit> class NegativeNumber
{
public:
NegativeNumber() : current(0) {};
int operator()()
{
return -(1 + (current++ % limit));
};
private:
int current;
};
Then, you can define any generator with any limit and use it:
NegativeNumber<5> five;
NegativeNumber<2> two;
for (int x = 0; x < 20; ++x)
std::cout << "limit five: " << five() << "\tlimit two: " << two() << '\n';
You can also pass the generator as parameter to another function, with each funtor with its own state:
void f5(NegativeNumber<5> &n)
{
std::cout << "limit five: " << n() << '\n';
}
void f2(NegativeNumber<2> &n)
{
std::cout << "limit two: " << n() << '\n';
}
f5(five);
f2(two);
If you don't like the template solution to declare the limit, there's also the no-template version:
class NegativeNumberNoTemplate
{
public:
NegativeNumberNoTemplate(int limit) : m_limit(limit), current(0) {};
int operator()()
{
return -(1 + (current++ % m_limit));
};
private:
const int m_limit;
int current;
};
Using as argument to a function works in the same way, and it's internal state is transfered as well:
void f(NegativeNumberNoTemplate &n)
{
std::cout << "no template: " << n() << '\n';
}
NegativeNumberNoTemplate notemplate(3);
f(notemplate);
I hope you don't want to use it with threading, they're not thread safe ;)
Here you have all the examples; hope it helps.
Something like.... (haven't compiled)
class myClass
{
int number = 0;
int GetValue ()
{
return - (number = ((number+1) % 101))
}
}
Even a simple problem like this could lead you to several approximations, both in the algorithmic solution and in the concrete usage of the programming language.
This was my first solution using C++03. I preferred to switch the sign after computing the value.
#include <iostream>
int GetNextID() {
// This variable is private to this function. Be careful of not calling it
// from multiple threads!
static int current_value = 0;
const int MAX_CYCLE_VALUE = 100;
return - (current_value++ % MAX_CYCLE_VALUE) - 1;
}
int main()
{
const int TOTAL_GETS = 500;
for (int i = 0; i < TOTAL_GETS; ++i)
std::cout << GetNextID() << std::endl;
}
A different solution taking into account that the integer modulo in C++ takes the sign of the dividend (!) as commented in the Wikipedia
#include <iostream>
int GetNextID() {
// This variable is private to this function. Be careful of not calling it
// from multiple threads!
static int current_value = 0;
const int MAX_CYCLE_VALUE = 10;
return (current_value-- % MAX_CYCLE_VALUE) - 1;
}
int main()
{
const int TOTAL_GETS = 50;
for (int i = 0; i < TOTAL_GETS; ++i)
std::cout << GetNextID() << std::endl;
}