Why is it not changing values of that variables? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have to change this program so that data of object star show actually name and nr_indeksu but i'am stuck. Any help? And sorry for variables names but in my laguage they have meaning believe me and for the mess.
#include <iostream>
using namespace std;
class student
{
private:
string imie_nazwisko_ = "NO_NAME";
unsigned int nr_indeksu_ = 0;
public:
student(string imie_nazwisko, unsigned int nr_indeksu);
void printDane()
{
cout << " Metoda printDane klasy bazowej" << endl;
cout << " imie nazwisko " << imie_nazwisko_ << endl;
cout << " nr indeksu " << nr_indeksu_ << endl;
}
};
class starosta : public student
{
public:
string imie_nazwisko_ = "NO_NAME";
unsigned int nr_indeksu_ = 0;
string email_ = "no#noemail";
void printDane()
{
cout << " Metoda printDane klasy starosta" << endl;
cout << " imie nazwisko " << imie_nazwisko_ << endl;
cout << " nr indeksu " << nr_indeksu_ << endl;
cout << " email "<< email_<<endl;
}
starosta(string imie_nazwisko, unsigned int nr_indeksu, string email);
};
starosta::starosta(string imie_nazwisko, unsigned int nr_indeksu, string email) :student(imie_nazwisko, nr_indeksu), email_(email)
{
cout << "Tworzenie obiektu klasy starosta "<< endl;
}
student::student(string imie_nazwisko, unsigned int nr_indeksu) : imie_nazwisko_(imie_nazwisko)
{
nr_indeksu_ = nr_indeksu;
cout << "Tworzenie obiektu klasy student" <<endl;
}
int main()
{
student stud("Jan Kowalski",7);
stud.printDane();
starosta star("Aleksandra Nowak",999,"mail#nomail.dot");
cout << "Dane:" << star.imie_nazwisko_ << " " << star.nr_indeksu_ << endl;
star.printDane();
}

You declare new members in the class starosta that already exist in the class student. Then you initialize the members of student using its constructor and try to print out the members of starosta in its method printDane. You should remove duplicated names from the class starosta.
class starosta : public student
{
public:
string imie_nazwisko_ = "NO_NAME"; // duplicates student::imie_nazwisko_
unsigned int nr_indeksu_ = 0; // duplicates student::nr_indeksu_

Related

C++ raises error: use of undeclared identifier c++ on calling constructor from header file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I keep getting the cpp/ItemsToPurchase.cpp:8:16: error: use of undeclared identifier 'name' this->itemName=name; on the following code. There are three files; ItemToPurchase.h, ItemToPurchase.cpp and main.cpp.
Any help would be appreciated.
ItemToPurchase.h
#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H
#include<iostream>
using namespace std;
class ItemToPurchase
{
public:
ItemToPurchase();
void setItemName(string name);
void setItemPrice(int itemPrice);
void setItemQuantity(int itemQuantity);
string getItemName();
int getItemPrice();
int getItemQuantity();
virtual ~ItemToPurchase();
protected:
private:
string itemName ;
int itemPrice;
int itemQuantity ;
};
#endif // ITEMTOPURCHASE_H
ItemToPurchase.cpp
#include <iostream>
#include "ItemToPurchase.h"
ItemToPurchase::ItemToPurchase()
{
this->itemName="none";
this->itemPrice=0;
this->itemQuantity=0;
this->itemName=name;
}
void ItemToPurchase::setItemPrice(int itemPrice)
{
this->itemPrice=itemPrice;
}
void ItemToPurchase::setItemQuantity(int itemQuantity)
{
this->itemQuantity=itemQuantity;
}
string ItemToPurchase::getItemName()
{
return itemName;
}
int ItemToPurchase::getItemPrice()
{
return itemPrice;
}
int ItemToPurchase::getItemQuantity()
{
return itemQuantity;
}
ItemToPurchase::~ItemToPurchase()
{
//dtor
}
main.cpp
#include <iostream>
#include "ItemToPurchase.h"
using namespace std;
int main()
{
ItemToPurchase item1,item2;
string itemName ;
int itemPrice;
int itemQuantity ;
int totalCost=0;
cout << "Item 1:" << endl;
cout << "Enter the item name : ";
getline(cin,itemName);
//cin.ignore();
cout << "Enter the item price : ";
cin >> itemPrice;
cout << "Enter the item quantity : ";
cin >> itemQuantity;
item1.setItemName(itemName);
item1.setItemPrice(itemPrice);
item1.setItemQuantity(itemQuantity);
cin.ignore();
cout << "Item 2:" << endl;
cout << "Enter the item name : ";
getline(cin,itemName);
//cin.ignore();
cout<<"Enter the item price : ";
cin>>itemPrice;
cout<<"Enter the item quantity : ";
cin>>itemQuantity;
item2.setItemName(itemName);
item2.setItemPrice(itemPrice);
item2.setItemQuantity(itemQuantity);
cout << "TOTAL COST : " << endl;
cout << item1.getItemName() << " " << item1.getItemQuantity() << " # $"
<< item1.getItemPrice() << " = " <<
(item1.getItemQuantity()*item1.getItemPrice()) << endl;
cout << item2.getItemName() << " " << item2.getItemQuantity() << " # $"
<< item2.getItemPrice() << " = " <<
(item2.getItemQuantity()*item2.getItemPrice()) << endl;
totalCost = (item1.getItemQuantity()*item1.getItemPrice()) + (item2.getItemQuantity()*item2.getItemPrice());
cout << "Total : $" << totalCost << endl;
return 0;
}
Just as the error message tells: There is no symbol name in the scope of the ItemToPurchase construcor.
ItemToPurchase::ItemToPurchase()
{
this->itemName="none"; // here you set name to "none"
this->itemPrice=0;
this->itemQuantity=0;
this->itemName=name; // here you try to set the name again
}
In main() you call a method setItemName which is not implemented as far I can tell it is only declared in the header file. I assume you tried to do something like:
ItemToPurchase::ItemToPurchase()
{
this->itemName="none"; // here you set the name to "none"
this->itemPrice=0;
this->itemQuantity=0;
}
ItemToPurchase::setItemName(std::string name)
{
this->itemName=name; // here you set the actual name
}
The only place an identifier name is declared in the source code you show is as a parameter of setItemName in ItemToPurchase.h. At the place where the error occurs, line 8 in ItemToPurchase.cpp, it is in the routine ItemToPurchase, and no declaration of name is in scope.
That explains the error message. As for correcting it, what do you expect this->itemName=name; to do? It has to know what name is so it can get its value. What name do you expect it to use? Or maybe you want to initialize itemName to an empty string or some default name like “unnamed item”?

I cannot use the static variable [duplicate]

This question already has answers here:
Undefined reference to a static member
(5 answers)
Closed 1 year ago.
I'm trying to print the employee count after each created object but I'm getting an error like this: undefined reference to `Employee::numberofEmployees'. How can I solve this little problem? Any ideas? Btw I'm using a local class.
the purpose of the numberofEmployees variable is to store the information on the number of employee objects created/instantiated so far.
#include <iostream>
#include <string>
using namespace std;
class Employee{
public:
string name;
string surname;
int year;
double salary;
static int numberofEmployees;
Employee(int yil,string isim,string soyisim): year(yil),name(isim),surname(soyisim){
numberofEmployees++;
}
Employee(){
name = "not-set";
year = 0;
surname = "not-set";
salary = 0.0;
}
void calculateSalary(){
salary = 2310 + 2310 * year * 12 / 100.0;
}
void printInfo(){
cout << name << " " << surname << " " << "(" << year << ")" << " " << salary << "TL/month" << endl;
}
};
int main()
{
Employee person1(4,"Berk","Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person2(8,"Esat","Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person3(20,"Paul","Walker");
cout << Employee::numberofEmployees << endl;
person1.calculateSalary();
person2.calculateSalary();
person3.calculateSalary();
person1.printInfo();
person2.printInfo();
person3.printInfo();
return 0;
}
You have to initialize your static data member outside the class using scope resolution operator something like this.
int Employee::numberofEmployees = 0;
This shows that you are accessing a static variable of class Employee and then initializing it.
If you have a static variable within a class, you are supposed to initialise it outside of the class, ie in a .cpp file. From C++17, however, you are allowed to initialise it in-class, in-line, using the inline keyword.
Code:
#include <string>
#include <iostream>
using namespace std;
class Employee
{
public:
string name;
string surname;
int year;
double salary;
static inline int numberofEmployees = 0;
Employee(int yil, string isim, string soyisim) : year(yil), name(isim), surname(soyisim)
{
numberofEmployees++;
}
Employee()
{
name = "not-set";
year = 0;
surname = "not-set";
salary = 0.0;
}
void calculateSalary()
{
salary = 2310 + 2310 * year * 12 / 100.0;
}
void printInfo()
{
cout << name << " " << surname << " "
<< "(" << year << ")"
<< " " << salary << "TL/month" << endl;
}
};
int main()
{
Employee person1(4, "Berk", "Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person2(8, "Esat", "Kandemir");
cout << Employee::numberofEmployees << endl;
Employee person3(20, "Paul", "Walker");
cout << Employee::numberofEmployees << endl;
person1.calculateSalary();
person2.calculateSalary();
person3.calculateSalary();
person1.printInfo();
person2.printInfo();
person3.printInfo();
return 0;
}
Or keep your code and add:
int Employee::numberofEmployees = 0;
After your class.
Output:
1
2
3
Berk Kandemir (4) 3418.8TL/month
Esat Kandemir (8) 4527.6TL/month
Paul Walker (20) 7854TL/month

private static variable accesing output is linker issues [duplicate]

This question already has answers here:
Undefined reference to static variable c++
(3 answers)
Closed 2 years ago.
I created a Class Student with instance data members
like studentname, studentaddress, studentrollno
i declared private static data member CollegeName that could be shared among all instances of class.
used promptfunction to take user input from the console
next functions to display student details.
Meanwhile resulting in below errors :
Meanwhile codes goes here:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int studentrollno;
string studentName;
string studentAddress;
static string CollegeName;
public:
void setRollNo(int rollno) {
studentrollno = rollno;
}
int getRollNo() {
return studentrollno;
}
void setName(string name) {
studentName = name;
}
string getName() {
return studentName;
}
void setAddress(string address) {
studentAddress = address;
}
string getAddress() {
return studentAddress;
}
static void setCollegeName(string collegename) {
CollegeName = collegename;
}
static string getCollegeName() {
return CollegeName;
}
void displayStudentDetails(); // member functions declare inside class Meanwhile it is defined
outside
static void show() {
cout << "this is static function " << endl;
}
};
// member functions define outside Student class
void Student :: displayStudentDetails() {
cout << "Student Name : " << getName() << " Student RollNo : " << getRollNo() << "Student Address
: " << getAddress() << "CollegeName: "<< getCollegeName() << endl;
}
void promptValues(Student &student) {
cout << "Enter the student Details " << endl;
cout << "Enter the details about student objects " << endl;
cout << endl;
int studentrollno;
string studentname , studentaddress ;
string collegename;
cout << "Enter the RollNo of the student " << endl;
cin >> studentrollno;
cout << "Enter the Name of the student " << endl;
cin >> studentname;
cout << endl;
cout << "Enter the address of the student " << endl;
cin >> studentaddress;
cout << endl;
cout << "Enter the collegeName of the student " << endl;
cin >> collegename;
student.setRollNo(studentrollno), student.setName(studentname), student.setAddress(studentaddress),
student.setCollegeName(collegename);
}
int main() {
Student student1, student2 , student3 , student4 , student5 ;
Student studentarrays[5] = { student1, student2, student3, student4, student5 };
Student studentmodel[5];
for (int i = 0; i < 5; i++) {
Student model;
model = studentarrays[i];
promptValues(model);
studentmodel[i] = model;
}
for (Student studentdetails : studentmodel) {
studentdetails.displayStudentDetails();
}
Student::show();
return 0;
}
You have omited the definition of the static member Student::CollegeName. It is only declared in the class, now you should define it after the class declaration with this:
std::string Student::CollegeName;
For more information see https://en.cppreference.com/w/cpp/language/static

Is it okay to have many parameters in a void function in C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm a beginner so please be nice :)
I already make the program work properly with the use of Global Variables. But I want to try using Local Variables because the Global Variables looks messy and I also found out that it is a bad practice to always use it. The program runs with the Local Variables but it doesn't work properly. I'm having a problem with the display of the results which is under the void function funcDataSummary. The void funcDataSummary works and the values of (float numberOfRooms, float wallSpace, float costOfPaint,...) which are inputted by the user is correct but the values of (..., float gallonsOfPaint, float totalCostOfPaint, float hoursOfLabor, float laborCost, float totalCost) is 0 when they should have a value.
Output with the use of Global Variables:
Output with the use of Local Variables:
#include <iostream>
#include <iomanip>
#include <windows.h>
using namespace std;
// function prototype
void funcDataSummary(float, float, float, float, float, float, float, float);
// void function called in int main()
funcDataSummary(numberOfRooms, wallSpace, costOfPaint, gallonsOfPaint, totalCostOfPaint, hoursOfLabor, laborCost, totalCost);
// void function
void funcDataSummary(float numberOfRooms, float wallSpace, float costOfPaint, float gallonsOfPaint, float totalCostOfPaint, float hoursOfLabor, float laborCost, float totalCost)
{
cout << "DETAILS" << endl;
cout << "Number of Rooms = " << funcNumberOfRooms(numberOfRooms) << endl;
cout << "Wall Dimension = " << funcWallSpace(wallSpace) << " square feet" << endl;
cout << "Paint Cost = Php " << funcCostOfPaint(costOfPaint) << endl;
cout << "Gallons of Paint = " << funcGallonsOfPaint(gallonsOfPaint);
// singular and plural forms of units
if(funcGallonsOfPaint(gallonsOfPaint) > 1)
{
cout << " Gallons" << endl;
}
else
{
cout << " Gallon" << endl;
}
cout << "Total Paint Cost = Php " << << funcTotalCostOfPaint(totalCostOfPaint) << endl;
cout << "Labor hours = " << funcHoursOfLabor(hoursOfLabor);
// singular and plural forms of units
if(funcHoursOfLabor(hoursOfLabor) > 1)
{
cout << " hours" << endl;
}
else
{
cout << " hour" << endl;
}
cout << "Labor Cost = Php " << funcLaborCost(laborCost) << endl;
cout << "TOTAL COST = Php " << funcTotalCost(totalCost) << endl;
}
Though it's okay, it makes your code a bit complicated.
If it's possible, it's better group related to each other variables in one or more struct or class and pass these objects (or pointer/reference/const reference if it is needed) as parameters.
My suggestion is to use immutable class to store all kind of stuff you need in your function and pass it as a const reference or pointer. Here is an example :
#include <iostream>
#include <string>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
class ParamsHolder : private boost::noncopyable
{
private :
std::string m_name;
std::uint32_t m_value;
public :
typedef boost::shared_ptr<ParamsHolder> pointer;
ParamsHolder( const std::string name, std::uint32_t value )
: m_name( name ), m_value( value ) {}
virtual ~ParamsHolder() {}
std::string getHolderName() const { return m_name; }
std::uint32_t getHolderValue() const { return m_value; }
};
void testFunction( ParamsHolder::pointer holder )
{
std::cout << holder->getHolderName() << std::endl;
std::cout << holder->getHolderValue() << std::endl;
}
int main()
{
std::cout << "Test program for holder" << std::endl;
std::string testName = "some name";
std::uint32_t testValue = 111;
auto holder = boost::make_shared<ParamsHolder>( testName, testValue );
testFunction( holder );
return 0;
}
To create a holder with many parameters have a look at builder design pattern or abstract factory.

arry of pointers ( classes )

So I have these classes:
In main I wrote an array of pointers:
student *arry[10];
How can I make each cell point to an object of a different class?
For example :
I want the cell 0 , 2 , 4
point to an object of class medstudent
using ( new statement )
thank you
here is class medStudent
#include<iostream>
#include"student.cpp"
using namespace std;
class medStudent:public student {
public :int clinicH;
public:
medStudent(int ch, string n , int i ):student(n,i){
setClinicH(ch);
cout << "New Medecine Student" << endl;
}
~medStudent(){
cout << "Medecine Student Deleted" << endl;
}
medStudent(medStudent & ms):student(ms){
cout << "New Copy Medecined Student" << endl;
}
medstudent(){
}
void setClinicH(int ch){
clinicH = ch;
}
int getClinicH()const{
return clinicH;
}
void print()const{
student::print();
cout << "Clinical Hours: " << getClinicH() << endl;
}
};
Here is class student:
#include <iostream>
//#include"medstudent.cpp"
using namespace std;
class student//:public medstudent
{
public :
static int numberOfSaeeds;
const int id;
string name;
public:
~student(){
cout << "Delete Student: " << getName() << " " << endl ;
}
student(string n, int i):id(i){
setName(n);
cout << "Student with args" << endl ;
}
void setName(string n){
name = n;
}
string getName()const{
return name;
}
void print()const{
cout << "My name is: " << name << endl;
cout << "My ID is: " << id << endl;
}
void setNOS(int nos){
numberOfSaeeds = nos;
}
int getNOS(){
return numberOfSaeeds;
}
void printAddress()const{
cout << "My address is " << this << endl;
}
student * getAddress(){
return this;
}
student(student & sc):id(sc.id){
name = sc.name;
setName(sc.getName());
cout << "New Object using the copy constructor" << endl;
}
};
Here is main code:
#include<iostream>
using namespace std;
#include"time.cpp"
#include "student.cpp"
//#include"medstudent.cpp"
int main(){
student a1("asa" , 2);
student * a[10];
a[3]= new student("jj", 22 );
a[0] = new medStudent();
}
Since you explicitly declare a medStudent constructor the compiler will not create a default constructor for your class. And when you do new medStudent(); you are (explicitly) trying to invoke the default constructor, which doesn't exist.
That will give you a build error, one that should have been very easy to diagnose if you read it and most importantly shown it to us (when asking questions about build errors, always include the complete and unedited error output, including any informational output, in the body of the question, together with the code causing the error).
The solution? Call the existing parameterized constructor. E.g. new medStudent("foo", 123).
By the way, if you want inheritance to work okay, and the base-class destructor to be called when deleting an object of a child-class, then you need to make the destructors virtual.