i want to know how can i declare a variable that contain boolean in it in the class section like as
class account {
char itemName[50];
double actualPrice;
bool empty= false;
public:
void create_account();
void displayRecord() const;
void drawLine3(int n, char symbol);
};
void
account::create_account()
{
do{
cout << "Type the name of Item " << endl;
cin.getline(itemName, 50);
}while(itemName!=empty);
cout << "Actual price :" << endl;
cin >> actualPrice;
cout << endl;
cout << "Item Name :-> " << itemName << endl;
cout << "Actual Price :->" << actualPrice << endl;
}
You should have a constructor to initialize class members:
class account {
char itemName[50];
double actualPrice;
bool empty;
public:
account() : empty(false) {} // this initializes the 'empty' variable to 'false'.
void create_account();
void displayRecord() const;
void drawLine3(int n, char symbol);
};
You cannot, except if your compiler is C++-11 compliant (in that case the syntax you wrote is correct), otherwise you should add a constructor that sets inital values for the variables that need an initialization:
class account {
public:
account() : itemName(""), actualPrice(0.0), empty(true) {}
[...]
};
PS: if your compiler is GCC or CLANG you can enable C++-11 compatibility through the command line switch -std=c++11
Related
i am trying to input a string in my code in c++ and when i run i always get the following error: Exception thrown at 0x0F5023F5 (msvcp140d.dll) in assignment-1.exe: 0xC0000005: Access violation writing location 0x00229C20. i will post my code below if anyone could help me that would be great.Please note that i already know that its a problem with me trying to access the memory location on which you dont have access to, i just dont know how to fix it.
HEADER FILE:
#ifndef item_H
#define item_h
class item
{
private:
//attributes
int itemID;
char itemName[20];
float itemcost;
float itemprice;
//utility function
float calcPrice();
public:
//constructor
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
//destructor
~item();
//set functions
void setAll(int, char[], float, float);
void setID(int);
void setName(char[]);
void setCost(float);
//get function
int getID();
float getcost();
float getprice();
void getname();
//print function
void print();
};
#endif
CPP:
#include "Dariush.h"
#include <iostream>
#include <iomanip>
#include<string>
using namespace std;
//constructor will set attributes
item::item(int ID, char n[] , float c,float p)
{
setID(ID);
setName(n);
setCost(c);
setAll(ID, n, c, p);
}
//destructor will print destroing two objects
item::~item()
{
cout << "destroing two objects : " << " " << itemName << " "
<< " & " << itemName << endl;
}
//set functions :
void item::setID(int ID)
{
cout << "please enter the item's ID : " << endl;
cin >> ID;
}
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20);
}
void item::setCost(float c)
{
cout << "please enter the item's cost : " << endl;
cin >> c;
}
void item::setAll(int ID, char n[], float c, float p)
{
itemID = (ID > 0 && ID < 999) ? ID : 0;
strcpy_s(itemName, n);
itemcost = (c > 0) ? c : 0;
calcPrice();
}
//get functions :
int item::getID()
{
return itemID;
}
float item::getcost()
{
return itemcost;
}
float item::getprice()
{
return itemprice;
}
void item::getname()
{
cout << itemName << endl;
}
//print function :
void item::print()
{
cout << "ID : " << itemID << endl
<< "Name : " << itemName << endl
<< "cost : " << itemcost << endl
<< "price : " << itemprice << endl;
}
// utility function for price callculation :
float item::calcPrice()
{
if (itemcost < 1000)
{
itemprice = itemcost + (itemcost*0.1);
}
else
itemprice = itemcost + (itemcost*0.2);
return itemprice;
}
MAIN.CPP:
#include "Dariush.h"
#include <iostream>
#include<string>
using namespace std ;
void main()
{
item i1;
item i2;
i1.print();
i2.print();
}
thanks for the assistance.
Lets take a closer look at these three function declarations:
item(int = 000, char[] = "itemUnknown", float = 0,float = 0);
void setAll(int, char[], float, float);
void setName(char[]);
The thing here is that the character "array" arguments you declare are not really arrays at all. Instead they are pointers. When declaring arguments, e.g. char n[] is actually translated by the compiler as char *n.
The constructor declaration makes the pointer point to the constant string literal "". And the important thing about constant string literals is that they are indeed constant. Trying to modify a string literal leads to undefined behavior. And change this literal is what you are trying to do with the cin.getline(n, 20) call in the setName function. Not only that, but you are also telling the cin.getline function to read more than fits in the string literal.
The simple solution is to have setName read into the member variable itemName instead.
There are many problems with this code, but the one that is causing the access violation is:
void item::setName(char n[])
{
cout << "please enter the item's name" << endl;
cin.ignore();
cin.getline(n, 20); //here
}
You should use cin.getline(itemName, 20); instead.
Also, to prevent such error in the future, declare arguments as char const n[] instead of char n[] - good compiler should display a warning when you use string literals with non-const pointer as argument.
The program is working in this way. But I need to change the price system. I need to use priceRead and priceWrite.
priceRead (): double
priceWrite (in _price: double): void
priceRead: price is a function to read the property.
priceWrite (double): price property is a function of writing.
Sorry for bad english. :(
#include <iostream>
#include <string.h>
using namespace std;
class shoes{
protected:
int size;
string colour;
char sex;
string brand;
public: shoes(int _size, string _colour, char _sex, string _brand)
:size(_size),colour(_colour), sex(_sex), brand(_brand)
{cout << "shoe configurator" << endl;}
~shoes(){ }
void shoesInf();
};
class storage{
protected:
int number;
int maxsize;
int minsize;
public: storage(int _number, int _maxsize, int _minsize)
:number(_number),maxsize(_maxsize),minsize(_minsize)
{cout << "store configurator" << endl;}
~storage(){ }
void storageInf();
};
void shoes::shoesInf()
{
cout << "Size :" << size << endl;
cout << "Colour :" << colour << endl;
cout << "Sex :" << ((sex=='M')?"Man":"Woman") << endl;
cout << "Brand:" << brand << endl;
}
void storage::storageInf()
{
cout << "Number :" << number << endl;
cout << "Max size :" << maxsize << endl;
cout << "Min size :" << minsize << endl;
}
class Store: public storage{
private: int number;
int maxsize;
int minsize;
public: Store(int _number, int _maxsize, int _minsize)
:storage(_number,_maxsize,_minsize)
{cout << "storage INF" << endl;}
};
class Nike: public shoes{
private: double price;
public: Nike(int _size, string _colour, char _sex, string _brand,
double _price):shoes(_size,_colour,_sex,_brand),price(_price)
{cout << "Shoes INF" << endl;}
void shoesInf()
{
((shoes*)this)->shoesInf();
cout << "Price :" << price << endl;
}
};
class Lacoste: public shoes{
private: double price;
public: Lacoste(int _size, string _colour, char _sex, string _brand,
double _price):shoes(_size,_colour,_sex,_brand),price(_price)
{cout << "Shoes INF" << endl;}
void shoesInf()
{
((shoes*)this)->shoesInf();
cout << "Price:" << price<< endl;
}
};
int main(int argc, char** argv) {
Store*sh=new Store(1,50,15);
sh->storageInf();
Nike *sh2=new Nike(38,"Blue",'F',"Nike",100);
sh2->shoesInf();
Lacoste *sh3=new Lacoste(40,"Yellow",'M',"Lacoste",350);
sh3->shoesInf();
return 0;
}
class Shoes
{
private:
int size;
string colour;
char sex;
string brand;
double price;
public:
Shoes(int _size, string _colour, char _sex, string _brand, double _price) :
size(_size), colour(_colour), sex(_sex), brand(_brand), price(_price)
{}
void writePrice(double newPrice)
{
price = newPrice;
}
void readPrice()
{
cout << price << endl;
}
};
Notes:
All shoes have a price, so why not just put it in the base class?
Brand is defined by the brand string, all shoes are the same, so no need to derive a new class for each brand.
No need to have an empty destructor.
Also, without this redefinition of price when deriving, you don't have to redefine shoeInf everytime you want to derive from Shoe.
One more thing: Start class names with CapitalLetters (in that style!).
My output name is not being displayed in my program. I have been looking at the code and
I just can't find my error
input
name : John Dough
id : 123445
start date : 10312014
shift: 2
output
name : ^^^^^^ <<<< I am having problem my name not being displayed
id : 123445
start date : 10312014
shift : 2
code
//This program demostrates a class and a derived class with constructors.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
char EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(char);
void setEmpNum(int);
void setHireDate(int);
char getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
void Employee::setEmpName(char x)
{
EmpName = x;
}
void Employee::setEmpNum(int y)
{
EmpNum = y;
}
void Employee::setHireDate(int z)
{
HireDate = z;
}
char Employee::getEmpName() const
{
return EmpName;
}
int Employee::getEmpNum() const
{
return EmpNum;
}
int Employee::getHireDate() const
{
return HireDate;
}
Employee::Employee()
{
cout << "I will ask you some questions about an employee.\n\n";
}
class ProductionWorker : public Employee
{
private:
int Shift;
double HourlyPayRate;
public:
void setShift(int);
void setHourlyPayRate(double);
int getShift() const;
double getHourlyPayRate() const;
ProductionWorker();
};
void ProductionWorker::setShift(int a)
{
Shift = a;
}
void ProductionWorker::setHourlyPayRate(double b)
{
HourlyPayRate = b;
}
int ProductionWorker::getShift() const
{
return Shift;
}
double ProductionWorker::getHourlyPayRate() const
{
return HourlyPayRate;
}
ProductionWorker::ProductionWorker()
{
cout << "After answering the questions,\n";
cout << "I will display the employee's information.\n\n\n";
}
int main()
{
ProductionWorker info;
char name[100];
int num;
int date;
int shift;
double rate;
cout << "What is the employee's name? ";
cin.getline(name, 100);
cout << "What is the employee's number? ";
cin >> num;
cout << "What is the employee's hire date?\n";
cout << "(Month, day, and year without any slashes,\n";
cout << "dashes, commas, or other punctuation.)\n";
cout << "For example, January 14, 1983 would look like 01141983. ";
cin >> date;
cout << "Does the employee work shift 1 or shift 2? ";
cin >> shift;
cout << "How much does the employee make per hour? ";
cin >> rate;
info.setEmpName(name[100]);
info.setEmpNum(num);
info.setHireDate(date);
info.setShift(shift);
info.setHourlyPayRate(rate);
cout << "\n\nHere is the employee's data:\n\n";
cout << "Employee's Name: " << info.getEmpName() << endl;
cout << "Employee's Number: " << info.getEmpNum() << endl;
cout << "Employee's Hire Date: " << info.getHireDate() << endl;
cout << "Employee's Shift: " << info.getShift() << endl;
cout << setprecision(2) << fixed;
cout << "Employee's Hourly Pay Rate: $" << info.getHourlyPayRate() << endl << endl;
return 0;
}
This is wrong: you're accessing an out-of-range character instead of passing the array to the function
char name[100];
//.. initialize name..
info.setEmpName(name[100]); // Accesses the 100th character (out-of-range [0-99])
void Employee::setEmpName(char x)
{
EmpName = x;
}
I would go for using std::string by changing EmpName (also wrong, it's not a single character) to a std::string
class Employee
{
private:
string EmpName;
int EmpNum;
int HireDate;
public:
void setEmpName(std::string& name);
void setEmpNum(int);
void setHireDate(int);
string getEmpName() const;
int getEmpNum() const;
int getHireDate() const;
Employee();
};
Also don't forget to change char name[100] to a std::string in the main function.
Live Example
You can of course accomplish this also with char arrays, in that case if you intend to use a fixed-size array you could either pass it by reference or just copy the content of a pointer to the array into a memory array for Employee.
There are multiple problems with your code.
First, the data type of Employee::EmpName should not be char. It should be a char array or even better would be a std::string.
Second the parameter of the setEmpName function should be either a const char* or a const std::string&.
Third, the name variable should perhaps be a std::string instead of a char array. Of course if you make that change the parameter of the setEmpName function should be const std::string&.
Fourth, when calling the setEmpName function you should just call it as follows: info.setEmpName(name).
Next, you should use std::getline(cin, name) instead of cin.getline(name, 100).
I'm first correcting your mistakes and then giving you a better alternative solution.
The member of your class and the setter function's parameter are only a single char. Change them to arrays:
char EmpName[100];
and
void setEmpName(char[]);
and in the implementation, you need to copy the content of the given array to your member:
void Employee::setEmpName(char[] x) {
memcpy(EmpName, x, 100);
}
However, this is the C way to do this.
The C++ way to do this is to use std::string. For this, change the types of the member, the parameters in the setter and in the getter as well as the type in main to std::string. To read a std::string, use the free-standing overload of getline which only takes the stream and the string (but no count):
getline(cin, name);
#include <iostream>
using namespace std;
class Vehicle{
protected:
string type;
int wheels;
bool engine; // number of engines in vehicle
public:
Vehicle(string t, int w,bool e):
type(t), wheels(w), engine(e){};
void setType(string t) {type = t;}
void setWheels(int w) {wheels = w;}
void setEngine(int e) {engine = e;} // number of engines, 0 - False.
string getType(){return type;}
int getWheels() {return wheels;}
bool getEngine() {cout << "1 - Has Engine | 0 - No Engine"; return engine;}
};
class Auto:public Vehicle {
private:
string brand;
int year;
public:
Auto(string t, int w, bool e, string b, int y):
Vehicle(t,w,e), brand(b),year(y) {};
void setBrand(string b) {brand = b;}
void setYear(int y) {year = y;}
string getBrand() {return brand;}
int getYear() {return year;}
};
int main()
{
// This first segment of the program demonstrates the relationship
// between the base class and derived class through the use of
// a constructor.
Auto Spider360("Car",4,2,"Ferrari",2000);
cout << "Car type: " << Spider360.getType() << endl;
cout << "Number of wheels: " << Spider360.getWheels() << endl;
cout << " Has Engine: " << Spider360.getEngine() << "\n";
cout << "Brand: " << Spider360.getBrand() << endl;
cout << "Year: " << Spider360.getYear() << "\n\n";
// Now I use member functions directly to assign values to an object
Auto SuperAmerica;
return 0;
}
I am unable to declare the object Auto SuperAmerica; I get the following error: "No matching function call for Auto::Auto()" and for SuperAmerica, i do not want to use a constructor to set the values, I want to use my Set functions.
The error of
"No matching function call for Auto::Auto()"
means that you cannot instantiate the class in the way you wanted. If you want to create the object and then initialize its members later, using setters, then use a default constructor.
I am trying to create a base class which is a template class and accepts, as a templace, some class. This base class in the parent class of two other classes which are themselves the parents of the final class. Thus, I have the traditional diamond problem in c++ with the addition that the root base class is a template class. Using virtual inheritance here does not quite do the trick.
Edit: Included some code (and corrected typos)
#include<iostream>
#include<string>
using namespace std;
template<class TemplateT>
class MainMaster {
protected:
std::string name;
int number;
TemplateT variableProp;
public:
explicit MainMaster(std::string, int);
void setName(std::string);
std::string getName();
void printName();
void setNumber(int);
int getNumber();
void printNumber();
void printMasterProperties(std::string);
void setVarProp(TemplateT);
TemplateT getVarProp();
};
template<class TemplateT>
MainMaster<TemplateT>::MainMaster(std::string nameIn, int numIn){
setName(nameIn);
setNumber(numIn);
}
template<class TemplateT>
void MainMaster<TemplateT>::setName(std::string nameIn){ name = nameIn; }
template<class TemplateT>
std::string MainMaster<TemplateT>::getName(){ return name; }
template<class TemplateT>
void MainMaster<TemplateT>::printName(){ cout << "Master's name is " << name << endl; }
template<class TemplateT>
void MainMaster<TemplateT>::setNumber(int numIn){ number = numIn; }
template<class TemplateT>
int MainMaster<TemplateT>::getNumber(){ return number; }
template<class TemplateT>
void MainMaster<TemplateT>::printNumber(){ cout << name << "'s number is " << number << endl; }
template<class TemplateT>
void MainMaster<TemplateT>::printMasterProperties(std::string pre = ""){
cout << pre << "Master Properties" << endl
<< pre << "-Number: " << number << endl;
}
class ChildOne: public virtual MainMaster<std::string>{
protected:
std::string propOne;
public:
// using MainMaster::MainMaster;
ChildOne(std::string nameIn, int numIn, std::string p1);
void printName();
void setPropOne(std::string);
std::string getPropOne();
void printOnesProps(std::string);
};
ChildOne::ChildOne(std::string nameIn, int numIn, std::string p1): MainMaster<std::string>(nameIn,numIn){
setPropOne(p1);
}
void ChildOne::printName(){ cout << "ChildOne's name is " << name << endl; }
void ChildOne::setPropOne(std::string propIn){ propOne = propIn; }
std::string ChildOne::getPropOne(){ return propOne; }
void ChildOne::printOnesProps(std::string pre = ""){
printMasterProperties("-");
cout << pre << "One Properties" << endl
<< pre << "-PropOne: " << propOne << endl;
}
class ChildTwo: public virtual MainMaster<int>{
protected:
std::string propTwo;
public:
ChildTwo(std::string nameIn, int numIn, std::string p2);
void printName();
void setPropTwo(std::string);
std::string getPropTwo();
void printTwosProps(std::string);
};
ChildTwo::ChildTwo(std::string nameIn, int numIn, std::string p2): MainMaster<int>(nameIn,numIn){
setPropTwo(p2);
}
void ChildTwo::printName(){
cout << "ChidTwo's name is " << name << endl;
}
void ChildTwo::setPropTwo(std::string propIn){ propTwo = propIn; }
std::string ChildTwo::getPropTwo(){ return propTwo; }
void ChildTwo::printTwosProps(std::string pre = ""){
printMasterProperties("-");
cout << pre << "Two Properties" << endl
<< pre << "-PropTwo: " << propTwo << endl;
}
class FinalChild: public ChildOne, public ChildTwo{
protected:
double finalProp;
public:
FinalChild(std::string nameIn, int num, std::string prop1 ,std::string prop2, double pFinal);
void printFinalProps(std::string);
};
FinalChild::FinalChild(std::string nameIn, int num, std::string prop1 ,std::string prop2, double pFinal):
ChildOne(nameIn, num, prop1),
ChildTwo(nameIn, num, prop2),
MainMaster(nameIn, num){
finalProp = pFinal;
}
void FinalChild::printFinalProps(std::string pre = ""){
printMasterProperties("-");
cout << pre << name << "'s Final Properties" << endl;
cout << pre << "-Number: " << number << endl;
cout << pre << "-PropOne: " << propOne << endl;
cout << pre << "-PropTwo: " << propTwo << endl;
cout << pre << "-finalProp " << finalProp << endl;
}
int main () {
MainMaster<char> master("Master", 0);
ChildOne child1("Child1",1,"P1One");
ChildTwo child2("Child2",2,"P2Two");
FinalChild finalC("FinalChild", 3, "P1Final", "P2Final", 3.0);
master.printMasterProperties();
child1.printOnesProps();
child2.printTwosProps();
finalC.printFinalProps();
}