Having issue with base constructors used in derived class - c++

I'm running a code in which I'm using two base classes and deriving a derived class from them. I'm calling both of their constructors in the Derived class and I'm giving arguments in main. When I compile it doesn't give me any kind of error. But when I try to run the program it doesn't run, I'm really confused!
Here is my code
#include <iostream>
#include<iomanip>
using namespace std;
class Date
{
int day;
int month;
int year;
public:
Date(int d,int m,int y)
{
day=d;
month=m;
year=y;
}
void display()
{
cout<<endl<<day<<"\\"<<month<<"\\"<<year<<endl;
}
void set()
{
cout<<"Enter day :";
cin>>day;
cout<<"Enter month :";
cin>>month;
cout<<"Enter year :";
cin>>year;
}
// sets the date members
};
class Time
{
int hour;
int minute;
int second;
public:
Time(int h,int min,int s)
{
hour=h;
minute=min;
second=s;
}
void display() // displays the time
{
cout<<endl<<hour<<":"<<minute<<":"<<second<<endl;
}
void set()
{
cout<<"Enter hour :";
cin>>hour;
cout<<"Enter minute :";
cin>>minute;
cout<<"Enter seconds :";
cin>>second;
}
// sets the time members
};
class DateAndTime : public Date, public Time
{
int digital;
public:
DateAndTime(int a,int b,int c,int d,int e,int f):
Date(a,b,c),Time(d,e,f)
{
}
void set()
{
Date:set();
Time:set();
}
void display()
{
Date:display();
Time:display();
}
// prints date and time
};
int main()
{
DateAndTime Watch(17,02,1999,03,36,56);
Watch.display();
Watch.set();
Watch.display();
return 0;
}

The function
void set()
{
Date:set();
Time:set();
}
is wrong but the compiler does not complain because it treats Date: and Time: as labels. If you separate the labels and the function calls, the function is:
void set()
{
Date: // Unused label.
set(); // Calls the function again, leading to infinite recursion
// and stack overflow.
Time: // Unused label.
set(); // The function never gets here.
}
You need to use:
void set()
{
Date::set();
Time::set();
}
You need to update display similarly. Use:
void display()
{
Date::display();
Time::display();
}

Related

How to relate user with a book (Library system) C++

I am doing a university project and I am making a Library System.
It has a few restrictions I cannot use what we haven't been taught (so no vectors or std:: things).
Now, I have some classes made.
(1) Date
(2) Book
(3) Student
(4) Library //Haven't made it yet
Now, when a student/user issues a book their account number is being saved in "Book" class and so is the return_date.
Now, I wish to make a pointer or use this-> operator or something that will be in Student class but point to a Book class.
So, when Student wants to see which books they have currently issued will be displayed.
I am not sure how to do that.
Should I make a Library class, give it an array of "Book" class by composition and then make a member function in "Student/User" class and display it there?
I really want to use new/delete keyword, this, or pointers to do this. It's not compulsory but it will help me understand those concepts.
The following are my Book, Student and Date classes.
Date Class:
class Date
{
int Day; //1-31 based on month
int Month; //1-12
int Year; //any year
int checkDay(int );
int Late_Days;
public:
static const int Days_per_Month[13];
Date()
{
Day=0;
Month=0;
Year=0;
}
Date (int dy, int mn, int yr)
{
if (mn>0 && mn <=12)
Month=mn;
else
{
Month=1;
cout<<"Month "<<mn<<" invalid. Set to month 1"<<endl;
}
Year=yr;
Day=checkDay(dy);
}
void setDay(int d) {Day=d;}
void setMonth(int m) {Month=m;}
void setYear(int y) {Year=y;}
void setLateDay(int LD) {Late_Days=LD;}
int getDay() {return Day;}
int getMonth() {return Month;}
int getYear() {return Year;}
int getLateDay() {return Late_Days;}
void Print_Date()
{
cout<<getDay()<<"/"<<getMonth()<<"/"<<getYear()<<endl;
//cout<<Day<<"/"<<Month<<"/"<<Year<<endl;
}
void Update_Date()
{
cout<<"\nEnter Day: ";
cin>>Day;
cout<<"Enter Month: ";
cin>>Month;
cout<<"Year: ";
cin>>Year;
}
void increment_date(int num)
{
int day;
int month_new;
// Day=Day+num;
setDay(getDay()+num);
if( getDay()>Days_per_Month[getMonth()] )
{
day=getDay()-Days_per_Month[getMonth()];
setDay(day);
setMonth(getMonth()+1);
if(Days_per_Month[getMonth()]>12)
{
month_new=1;
setMonth(month_new);
setYear(getYear()+1);
}
}
Print_Date();
}
const int Date:: Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
int Date::checkDay(int testday) //returntype classname :: funcname (parameteres)
{
//static const int Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
if(testday > 0 && testday <= Days_per_Month[Month])
return testday;
if ( Month==2 && testday==29 && (Year%400==0 || (Year%4==0 && Year%100!=0)) ) //for leap year
return testday;
cout<<"Day "<<testday<<" invalid. Set to day 1."<<endl;
return 1;
}
Book Class
class Book
{
string Title;
string Author;
unsigned long int ISBN;
int Year_of_Publication;
int Library_Code;
string Category;
string Status;
unsigned int Account_Number; //if issued
int Copies_of_Book;
Date Return_Date;
public:
static int Copy_Number;
Book()
{
Title=" ";
Author=" ";
ISBN=0;
Year_of_Publication=0;
Library_Code=0;
Category=" ";
Status=" ";
Account_Number=0;
Copies_of_Book=0;
Return_Date.setDay(0);
Return_Date.setMonth(0);
Return_Date.setYear(0);
}
Book(string t, string a,unsigned long int isbn, int yop, int libcode, string c, string s, unsigned int an, int cob)
{
setTitle(t);
setAuthor(a);
setISBN(isbn);
setYOP(yop);
setLibraryCode(libcode);
setCategory(c);
setStatus(s);
setAccountNum(an);
setCopiesBook(cob);
}
void setTitle(string T) {Title=T;}
void setAuthor(string A) {Author=A;}
void setISBN(unsigned long int isbn){ISBN=isbn;}
void setYOP(int yop) {Year_of_Publication=yop;}
void setLibraryCode(int libcode) {Library_Code=libcode;}
void setCategory(string c) {Category=c;}
void setStatus(string s) {Status=s;}
void setAccountNum(unsigned int an) {Account_Number=an;}
void setCopiesBook(int cob) {Copies_of_Book=cob;}
void setCopyNumber(int cn) {Copy_Number=cn;}
string getTitle() {return Title;}
string getAuthor() {return Author;}
unsigned long int getISBN() {return ISBN;}
int getYOP() {return Year_of_Publication;}
int getLibraryCode() {return Library_Code;}
string getCategory() {return Category;}
string getStatus() {return Status;}
unsigned int getAccountNum() {return Account_Number;}
int getCopiesBook() {return Copies_of_Book;}
int getCopyNumber() {return Copy_Number;}
void Input_New_Book()
{
cout<<"\nEnter Title: ";
cin>>Title;
cout<<"Enter Author: ";
cin>>Author;
cout<<"Enter ISBN: ";
cin>>ISBN;
cout<<"Enter Year of Publication: ";
cin>>Year_of_Publication;
cout<<"Enter Library Code: ";
cin>>Library_Code;
cout<<"Enter Category: ";
cin>>Category;
cout<<"Enter Total Copies Number: ";
cin>>Copies_of_Book;
cout<<"Enter Status: ";
cin>>Status;
if(Status=="Issued")
{
cout<<"Enter Account Number: ";
cin>>Account_Number;
Return_Date.Update_Date();
}
}
void Display_Book_Info()
{
cout<<"\nTitle: "<<getTitle()<<endl;
cout<<"Author: "<<getAuthor()<<endl;
cout<<"ISBN: "<<getISBN()<<endl;
cout<<"Year of Publication: "<<getYOP()<<endl;
cout<<"Library Code: "<<getLibraryCode()<<endl;
cout<<"Category: "<<getCategory()<<endl;
cout<<"Total Copies: "<<getCopiesBook()<<endl;
cout<<"Status: "<<getStatus()<<endl;
if(getStatus()=="Issued")
{
cout<<"Account Number: "<<getAccountNum()<<endl;
cout<<"Return Date: ";
Return_Date.Print_Date();
}
}
void Update_Status()
{
unsigned int AN;
Display_Book_Info();
cout<<"Please enter the updated status of the book: ";
cin>>Status; //We cannot use string in an switch, so we are using if.
if (Status=="Lost")
{
cout<<"The book is lost."<<endl;
setAccountNum(0);
}
else if (Status=="Available")
{
cout<<"Book is available now to issue."<<endl;
setAccountNum(0); //This indicates it doesn't have nay account number.
}
else if(Status=="Issued")
{
cout<<"The book is in possession of someone."<<endl;
cout<<"Enter their account number:";
cin>>AN;
setAccountNum(AN);
}
else if (Status=="Order")
{
cout<<"The book is in process of being ordered."<<endl;
setAccountNum(0);
}
else
{
cout<<"Wrong entry!\nBook's Status is set to default. (Available)"<<endl;
Status="Available";
setAccountNum(0);
}
cout<<"Status updated successfully!"<<endl;
}
void Issue_Book(int day_num) //This day_num indicated number of days.
{
unsigned int an;
cout<<"Enter account number of User:";
cin>>an;
setAccountNum(an);
Return_Date.Update_Date();
cout<<"Book issued for "<<day_num<<" days."<<endl;
cout<<"Return Date: ";
Return_Date.Print_Date();
}
void ReIssue_Book(int day_num)
{
unsigned int an;
cout<<"Enter account number of User:";
cin>>an;
setAccountNum(an);
Return_Date.increment_date(day_num);
cout<<"Book issued for "<<day_num<<" more days."<<endl;
cout<<"Return Date: ";
Return_Date.Print_Date();
}
void Return_Book()
{
cout<<"Book returned from User: "<<getAccountNum()<<endl;
setAccountNum(0);
cout<<"Book returned successfully!"<<endl;
}
}; //end of class book
int Book::Copy_Number=0;
Student Class
class Student:public Book
{
string Name;
unsigned int Account_Number;
double Fine;
int Books_Issue;
public:
Student()
{
Name=" ";
Account_Number=0;
Fine=0;
Books_Issue=0;
}
void setName(string n) {Name=n;}
void setAccount_Number(unsigned int an) {Account_Number=an;}
void setFine(double f) {Fine=f;}
void setBooksIssue(int n) {Books_Issue=n;}
string getName() {return Name;}
unsigned int getAccount_Number() {return Account_Number;}
double getFine() {return Fine;}
int getBooksIssue() {return Books_Issue;}
void Input_Student_info()
{
cout<<"\nEnter Name: ";
cin>>Name;
cout<<"Enter Account Number: ";
cin>>Account_Number;
}
void Display_Student_info()
{
cout<<"Name: "<<getName()<<endl;
cout<<"Account Number: "<<getAccount_Number()<<endl;
cout<<"Total Fine: "<<getFine()<<endl;
cout<<"Books issued: "<<getBooksIssue()<<endl;
}
void Issue_a_book()
{
if(Books_Issue<=3)
{
Issue_Book(7); //This will issue a book and give it a 7 days return date time
Books_Issue++; //This will mean a book has been issued.
}
else
cout<<"Cannot issue book. You have reached your maximum limit.\nReturn a book in order to issue another."<<endl;
}
void Display_All_Books() //which are currently issued
{
for (int i=0 ; i<=getBooksIssue() ; i++)
{
}
}
};
Sorry for posting huge chunks of code. But some people say we should post the whole code, so this is why I posted all of it organized way.
The main question is:
How should I display issued books in a Student's class?
Should I make a Library class (as a parent class or child class, or use composition and arrays of Book class) first or at the very end?
Let me know what is the best way to do this.
Thank You so much.
It is better to have remove the user issue details from the book class...
Let the book class have only details about the book and methods to update and retrieve book details.
Add the user issue details into a new class which inherits the book class... This way is more modular and keeps the books as separate entities. Now you can make a linked list(as they are dynamic) or array of these classes, each holding a book and the issue and return dates for that particular student.
for example:
class books_issued{
public: book issued_book;
books_issued *new;
<put your issue data like:>
unsigned int Account_Number; //if issued
int Copies_of_Book;
Date Return_Date;
<and issue related methods:>
};
now declare an object of books_issued class in student class,
and write a method to add, remove and view books that have been issued by that particular student.
--- If you need any help with creating linked lists for this purpose, let me know I will be more than happy to help as I had done a very similar library management program for my project as well :-) ---

Remove warning of deprecated conversion from string constant to 'char*

I have written a code like bill payment. Code is working fine but there are many warnings in my code which I want to remove. One of the most frequent warning is deprecated conversion from string constant to 'char* . I have tried many things and some of the warnings are gone but not all. Please anybody point out at my mistakes??
P.S: I have already tried replacing char* to const char* , but then I am not able to exchange or swap values and it was causing error. Any other solution??
Below is the code
#include<iostream>
#include<string.h>
using namespace std;
class item
{
private:
int barcode;
char* item_name;
public:
item (int num=0, char* name="NULL") : barcode(num)
{
item_name=new char[strlen(name)+1];
strcpy(item_name,name);
}
void setbarcode(int num)
{
barcode=num;
}
int getbarcode()
{
return barcode;
}
void scanner()
{
int num;
cin>>num;
setbarcode(num);
}
void printer()
{
cout <<"\nBarcode"<<"\t\t"<<"Item Name"<<"\t\t"<<"Price"<<endl;
cout <<barcode<<"\t\t"<<item_name<<"\t\t\t";
}
~item()
{
delete[]item_name;
}
};
class packedfood : public item
{
private :
int price_per_piece;
public :
packedfood(int a=0, int num=0, char* name = "NULL") : price_per_piece(a),item(num,name)
{
}
void setprice(int num)
{
price_per_piece=num;
}
int getprice()
{
return price_per_piece;
}
void scanner()
{
item::scanner();
}
void printer()
{
item::printer();
cout<<getprice()<<" Per Piece";
}
~packedfood()
{
}
};
class freshfood: public item
{
private:
int price_per_rupee;
float weight;
public:
freshfood(float b=0, int a=0,int num=0,char* name="NULL") : weight(b),price_per_rupee(a),item(num,name)
{
}
void setweight(float b)
{
weight=b;
}
int getweight()
{
return weight*50;
}
void printer()
{
item::printer();
cout<<getweight()<<" Per Rupee"<<endl<<endl;
}
void scanner()
{
item::scanner();
}
~freshfood()
{
}
};
int main()
{
item x(389,"Anything");
item y;
packedfood m(10,118,"Chocolate");
packedfood n;
freshfood r(20.9,93,357,"Fruits");
freshfood s;
cout <<"\n\n Enter the Barcode for Packed food : ";
m.scanner();
m.printer();
cout <<"\n\n Enter the Barcode for Fresh food : ";
r.scanner();
r.printer();
system("PAUSE");
return 0;
}

Program exit without input and it has base,drived class properties initialization issues

It has two issues
1). program is not taking input it exits without getting value of variable option.
2).Also my base and derived class are not initializing they are displaying garbage value.
Here is complete code.
#include<iostream>
using namespace std;
class BeverageItem
{
protected:
string name;
double price;
public:
void set_name(string n);
string get_name();
void set_price(double pr);
double get_price();
};
void BeverageItem::set_name(string n)
{
name=n;
}
string BeverageItem::get_name()
{
return(name);
}
void BeverageItem::set_price(double pr)
{
price=pr;
}
double BeverageItem::get_price()
{
return(price);
}
class HotBeverage:public BeverageItem
{
private:
int tea_bags;
int whiteners;
public:
//HotBeverage(int bg,int wht);
void set_teabags(int t_bags);
int get_teabags();
int getwhiteners();
void set_whiteners(int wht);
double basePrice();
double computeTax();
double totalCost();
void print();
};
double HotBeverage::computeTax()
{
return (0.16*price);
}
double HotBeverage::totalCost()
{
return(price+computeTax());
}
double HotBeverage::basePrice()
{
double pr;
if((tea_bags==1)&& (whiteners==1))
{
pr=20;
}
else if((tea_bags>1)&& (whiteners>1))
{
tea_bags=tea_bags-1;
pr=20+(5*tea_bags);
}
set_price(pr);
return(pr);
}
void HotBeverage::set_teabags(int t_bags)
{
tea_bags=t_bags;
}
int HotBeverage::get_teabags()
{
return(tea_bags);
}
int HotBeverage::HotBeverage::getwhiteners()
{
return(whiteners);
}
void HotBeverage::set_whiteners(int wht)
{
whiteners=wht;
}
void HotBeverage::print()
{
cout<<"Name: "<<name<<endl;
cout<<"Tax:"<<computeTax()<<endl;
cout<<"Total Cost: "<<totalCost()<<endl;
}
class ColdBeverage:public BeverageItem
{
private:
int drinkSize;
public:
//ColdBeverage(int drinkSize);
void setDrinkSsize(int sz);
int getDrinkSize();
double basePrice();
double computeTax();
double totalCost();
void print();
};
void ColdBeverage::print()
{
cout<<"Name: "<<name<<endl;
cout<<"Tax:"<<computeTax()<<endl;
cout<<"Total Cost: "<<totalCost()<<endl;
}
void ColdBeverage::setDrinkSsize(int sz)
{
drinkSize=sz;
}
int ColdBeverage::getDrinkSize()
{
return(drinkSize);
}
double ColdBeverage::computeTax()
{
return (0.16*price);
}
double ColdBeverage::totalCost()
{
return(price+computeTax());
}
double ColdBeverage::basePrice()
{
double pr;
double regularPr=30;
switch(drinkSize)
{
case 1: //regular,
pr=regularPr;
break;
case 2: //large.
price=1.5*regularPr;
break;
case 3: //extra large.
price=2*regularPr;
break;
}
set_price(pr);
return(pr);
}
int main()
{
string name;
int option;
cout<<"Enter The Beverage Name=";
cin>>name;
cout<<"1. For Hot Beverage\n\n";
cout<<"2. For Cold Beverage\n\n";
cout<<"Select Your Choice(1,2)=";
cin>>option;
BeverageItem bi;
bi.set_name(name);
**//some other code here.**
return 0;
}
1) I don't really see a problem with the compiler i tried with
http://cpp.sh/4p5mw
2) POD's in member variables are not default initialised.
https://stackoverflow.com/a/15212447/4669663
Here was the issue
cin>>name;
cin stops when whitespaces are entered in a string so I would have to use
getline(cin,name);
Second issue was because i was not calling the basePrice() before print()
thanks to everyone

Parsing returned value to a another method

I want float variable 'avg' to be returned and then in the main pass it to 'void batsman::display(float a)' using a parameter. then display the average marks in display method. this method gives me 2 errors. any other way?
#include<iostream.h>
class batsman
{
int marks[5];
char name[15],country[15];
public:
void input();
float cal();
void display();
};
void batsman::input()
{
int i;
cout<<"Enter player name: ";
cin>>name;
cout<<"Enter player country: ";
cin>>country;
cout<<"Enter player marks"<<"\n";
for(i=0;i<5;i++)
{
cout<<"Mark "<<i+1<<": ";
cin>>marks[i];
}
}
float batsman::cal()
{
int i;
int tot=0;
float avg;
for(i=0;i<5;i++)
{
tot=tot+marks[i];
}
avg=(float)tot/5;
return avg;
}
void batsman::display(float a)
{
float avg1;
avg1=a;
cout<<"Player name: "<<name<<"\n";
cout<<"Player country: "<<country<<"\n";
cout<<"Average: "<<avg1<<"\n";
}
int main()
{
batsman b1;
b1.input();
b1.cal();
b1.display(b1.batsman::cal());
//cout<<"Average: "<<b1.batsman::cal()<<"\n";
}
The code has several errors.
iostream.h should be iostream
using namespace std; // add this at top so that cout is found
display() should be display(float a) in the class declaration.
After those changes the code ran as expected.
Change display's definition in your class to display(float a), and prepend std:: to cout and cin. As a recommendation, don't use iostream.h, use iostream.

Using constructor when passing an array of objects through composition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
#include <iostream>
#include <cstring>
using namespace std;
class assistantnurse{
private:
char* id;
char dutytime;
public:
assistantnurse(char[] ="", char =' ');
void setid(char*);
void setdutytime(char);
char* getid()const;
char getdutytime()const;
void print()const;
void inputinfo();
~assistantnurse();
};
assistantnurse::~assistantnurse()
{
delete[] id;
id=0;
}
assistantnurse::assistantnurse(char* i, char t)
{
setid(i);
setdutytime(t);
}
void assistantnurse::setid(char *i)
{
int l=strlen(i);
id=new char[l+1];
strncpy(id,i,l);
id[l]='\0';
}
void assistantnurse::setdutytime(char t)
{
dutytime=t;
}
char* assistantnurse::getid()const{return id;}
char assistantnurse::getdutytime()const{return dutytime;}
void assistantnurse::print()const
{
cout<<"ID: "<<id<<endl;
cout<<"Duty time: "<<dutytime<<endl<<endl;
}
void assistantnurse::inputinfo()
{
char nurseid[20];
char time;
cout<<"Enter nurse ID: ";
cin>>nurseid;
do
{
cout<<"Enter nurse Duty time(d for day/n for night): ";
cin>>time;
}while(time!='n' && time!='d');
setid(nurseid);
setdutytime(time);
}
class treatingphysician{
private:
char* id;
char* phonenumber;
assistantnurse assistant[2]; //3 assistant nurses through composition from assistantnurse class
public:
void setid(char*);
void setphonenumber(char*);
char* getid()const;
char* getphonenumber()const;
void setnurse();
void getnurse()const;
treatingphysician(char[] =" ", char[] =" ", assistantnurse[]);
~treatingphysician();
void print()const;
void inputinfo();
};
void treatingphysician::inputinfo()
{
char i[20];
char p[15];
cout<<"Enter physician ID: ";
cin>>i;
setid(i);
cout<<"Enter physican phone number: ";
cin>>p;
setphonenumber(p);
setnurse();
}
void treatingphysician::print()const
{
cout<<"Physician ID: "<<id<<endl;
cout<<"Physician phone number: "<<phonenumber<<endl<<endl;
getnurse();
}
treatingphysician::~treatingphysician()
{
delete[] id;
id=0;
delete[] phonenumber;
phonenumber=0;
}
treatingphysician::treatingphysician(char*i, char*p, assistantnurse k[2]):assistant(k)
{
setid(i);
setphonenumber(p);
}
void treatingphysician::setid(char*i)
{
int l=strlen(i);
id=new char[l+1];
strncpy(id,i,l);
id[l]='\0';
}
void treatingphysician::setphonenumber(char*p)
{
int l=strlen(p);
phonenumber=new char[l+1];
strncpy(phonenumber,p,l);
phonenumber[l]='\0';
}
char* treatingphysician::getid()const{return id;}
char* treatingphysician::getphonenumber()const{return phonenumber;}
void treatingphysician::setnurse()
{
for(int i=0;i<3;i++)
{
cout<<"Enter info for nurse #"<<i+1<<endl;
assistant[i].inputinfo();
cout<<"\n";
}
}
void treatingphysician::getnurse()const
{
for(int i=0;i<3;i++)
{
cout<<"Nurse #"<<i+1<<" ";
assistant[i].print();
}
}
int main()
{
treatingphysician e;
e.inputinfo();
e.print();
system("pause");
return 0;
}
two classes;
A nurse class and a physician class;
The physician has 3 nurses and all his attributes.
Using composition to fix this, but i'm stuck on the array of objects for the 3 nurses.
In my second constructor i faced a problem i used to work on composition before with the same method but the only difference is that it wasn't an array of objects used in composition. now I'm stuck.. Please Help
Short example...
`class A{
public:
A();
};
class B{
private:
A a[2];
public:
B(A[]);
};
B::B(A c[2]):a(c){}`
Use std::vector instead of raw arrays.
class A
{
public:
A();
};
typedef std::vector< A > A_vector;
class B
{
private:
A_vector m_a;
public:
B( A_vector av ) : m_a( av )
{
}
};