Cannot create pointers of an abstract class in function main() - c++

#include<iostream.h>
#include<conio.h>
#include<string.h>
class flight
{
private :
int flightno;
char source[30],destination[30];
protected :
double fare;
public :
flight()
{
flightno=0;
source[0]='\0';
destination[0]='\0';
fare=0.0 ;
}
flight(int f,char s[],char d[],double fr)
{
flightno=f;
strcpy(source,s);
strcpy(destination,d);
fare=fr;
}
flight(flight &f)
{
flightno=f.flightno;
strcpy(source,f.source);
strcpy(destination,f.destination);
fare=f.fare;
}
virtual void accept()
{
cout<<"\nEnter Fligt no :";
cin>>flightno;
cout<<"\nEnter source :";
cin.getline(source,30);
cout<<"\nEnter destination :";
cin.getline(destination,30);
cout<<"\nEnter fare :";
cin>>fare;
}
virtual void display()
{
cout<<"\nFlight number :"<<flightno;
cout<<"\nsource :"<<source;
cout<<"\nDestination :"<<destination;
cout<<"\nflight fare :"<<fare;
}
virtual double computefare()=0;
};
class domestic : public flight
{
private :
int noc,noa;
double totalfare,discount;
public :
domestic()
{
noc=0;
noa=0;
totalfare=0.0;
discount=0.0;
}
domestic(int f,char s[],char d[],double fr,int nc,int na):flight(f,s,d,fr)
{
noc=nc;
noa=na;
totalfare=0.0;
discount=0.0;
}
domestic(domestic &d):flight(d)
{
noc=d.noc;
noa=d.noa;
totalfare=d.totalfare;
discount=d.discount;
}
void accept()
{
flight::accept();
cout<<"\nEnter no. of adults :";
cin>>noa;
cout<<"\nEnter no. of children :";
cin>>noc;
}
void display()
{
flight::display();
cout<<"\n no. of adults :"<<noa;
cout<<"\n no. of children :"<<noc;
cout<<"\n total fare :"<<totalfare;
cout<<"\n discount :"<<discount;
if(discount!=0)
cout<<"After disc: "<<(totalfare-discount);
}
double computefare()
{
totalfare=noc*flight::fare*0.5+noa*flight::fare;
if(totalfare>40000)
discount=0.02*totalfare;
return totalfare-discount;
}
};
class internatinal : public flight
{
private :
int nop;
double totalfare,tax;
public :
internatinal()
{
nop=0;
totalfare=0.0;
tax=0.0;
}
internatinal(int f,char s[],char d[],double fr,int np):flight(f,s,d,fr)
{
nop=np;
totalfare=0.0;
tax=0.0;
}
internatinal(internatinal &i):flight(i)
{
nop=i.nop;
totalfare=i.totalfare;
tax=i.tax;
}
void accept()
{
flight::accept();
cout<<"\nEnter no. of passenger :";
cin>>nop;
}
void display()
{
flight::display();
cout<<"\n no. of passenger :"<<nop;
cout<<"\n total fare :"<<totalfare;
cout<<"\n tax :"<<tax;
cout<<"After tax: "<<(totalfare+tax);
}
double computefare()
{
totalfare=nop*flight::fare;
tax=0.30*totalfare;
return totalfare+tax;
}
};
int main()
{
int i,n,ch;
double total=0;
cout<<"\n Enter no of transaction :" ;
cin>>n;
flight *f=new flight[n];
for(i=0;i<n;i++)
{
cout<<"\n Enter 1 : domestic \n 2. internatinal :";
cin>>ch;
f[i]=ch==1?new domestic():new internatinal();
f[i]->accept();
total+=f[i]->computefare();
}
cout<<"\n totaL fare :"<<total;
getch();
return 0;
}
I am using turdo C++ complier . My code is not able to compile the error lies in the main() in "flight *f=new flight[n];" line (error is :1.)Cannot create instance of abstract
class 'flight' in function main()
2.) Class 'flight' is abstract because of 'flight::computefare() = 0' in function main() ).
As far as i can remember we cannot create objects of an abstract class but we can create pointers of it. And here i am creating pointers only but still m getting this error.

You're creating a pointer-to-flight, but you're also trying to create n flight objects: the array you're creating is an array-of-flight, not an array-of-pointer-to-flight.
So this cannot work.
You could use for instance a std::vector<flight*> (possibly using a smart pointer inside the container too). (Or an array of pointer-to-flight.)
For your assignment, don't try and scrunch it all up in a single line, it buys you nothing. Write it more clearly and it will work:
if (ch == 1)
f[i] = new domestic();
else
f[i] = new internatinal();
(The other option is to use a cast, but that will make that line even less readable.)

Related

needed help in solving of inheritance problem in c++ problem

I have a C++ question regarding inheritance:
Write a program that has a class Train with data members seats_first_class, seats_second_class and seats_ac_2tier and member functions to set and display data.
Derive a class Reservation that has data members booked_first_class, booked_second_class and booked_ac_2tier and functions to book and cancel tickets and display status.
This is the code which I have written
https://onlinegdb.com/CTAdFBM_C
#include <iostream>
using namespace std;
class Train
{
protected :
int seats_first_class,seats_second_class,seats_ac_2tier;
public :
//Train(int a,int b,int c) : seats_first_class(a),seats_second_class(b),seats_ac_2tier(c){}
//Train() : seats_first_class(0),seats_second_class(0),seats_ac_2tier(0){}
void Read()
{
cout<<"Enter the seats in 1st class..."; cin>>seats_first_class; cout<<endl;
cout<<"Enter the seats in 2nd class..."; cin>>seats_second_class; cout<<endl;
cout<<"Enter the seats in AC 2 tier..."; cin>>seats_ac_2tier; cout<<endl;
}
void Disp()
{
cout<<"The number of seats in booked by you in 1st class are "<<seats_first_class<<endl;
cout<<"The number of seats in booked by you in 2nd class are "<<seats_second_class<<endl;
cout<<"The number of seats in booked by you in AC 2 tier class are "<<seats_ac_2tier<<endl;
}
};
class Reservation : public Train
{
protected :
bool booked_first_class=0,booked_second_class=0,booked_ac_2tier=0;
public :
bool evaluvate_seat()
{
char ch;
cout<<"Have you booked tickets for 1st class\n"; cin>>ch;
if(ch='y')
return booked_first_class=true;
cout<<"Have you booked tickets for 2nd class\n"; cin>>ch;
if(ch='y')
return booked_second_class=true;
cout<<"Have you booked tickets for AC 2 tier\n"; cin>>ch;
if(ch='y')
return booked_ac_2tier=true;
}
void status_disp(bool a)
{
if(a==true)
cout<<"Status : Reserved"<<endl;
else
cout<<"Status : Not Reserved"<<endl;
}
void cancel_seat()
{
int n;
cout<<"Enter the the type of compartment you want to delete\n"; cin>>n;
switch(n)
{
case 1:
cout<<"Cancelling your ticket in 1st class"<<endl;
booked_first_class=false;
break;
case 2:
cout<<"Cancelling your ticket in 2nd class"<<endl;
booked_second_class=false;
break;
case 3:
cout<<"Cancelling your ticket in AC 2 tier class"<<endl;
booked_ac_2tier=false;
break;
}
}
};
int main()
{
Reservation r1,r2;//Train t1,t2;
r1.Read(); r2.Read();
r1.Disp(); r2.Disp();
r1.evaluvate_seat(); r1.status_disp(Resevation :: evaluvate_seat());
r2.cancel_seat(); r2.status_disp(Resevation :: evaluvate_seat());
return 0;
}
These are the errors i am facing:
main.cpp:76:38: error: ‘Resevation’ has not been declared
r1.evaluvate_seat(); r1.status_disp(Resevation :: evaluvate_seat());
^~~~~~~~~~
main.cpp:77:35: error: ‘Resevation’ has not been declared
r2.cancel_seat(); r2.status_disp(Resevation :: evaluvate_seat());
Edit :
I tried to rectify some mistakes but still am not successful in making the code error free. Anyone's help is really appreciable

I am trying to create a vehicle registration portal. For some reason the get() is only receiving the owner name

I am trying to create a vehicle registration portal. For some reason, the get() is only receiving the owner's name.
I'm trying to practice inheritance and used the concept of inheriting properties from the parent class "vehicle".
This one is the child class "get info"
#include<iostream>
using namespace std;
class vehicle{
private:
int noPlate;
char owner;
int registrationNo;
public:
int modelNo;
void setnoPlate_setRegNo_setOwner( char number, int rNumber, char ownerName){
noPlate = number;
registrationNo = rNumber;
owner = ownerName;
}
void displayInfo(){
cout<<"***Vehicle Information Portal***";
cout<<" ----------- \n";
cout<<"Owner Name: "<<owner<<"\n";
cout<<"Registered Number Plate: "<<noPlate<<"\n";
cout<<"Registration Numaber: "<<registrationNo<<"\n";
}
};
INHERITING VEHICLE CLASS
class getInfo : public vehicle{
public:
void get(){
char tempNoPlate;
int tempRegNumber;
char tempOwnerName;
cout<<"\n***Vehicle Registration Portal*** \n";
cout<<" ----------- \n";
cout<<"Enter your Registratered Owner name for your vehice:"<<"\n";
cin>>tempRegNumber;
cout<<"Enter your number plate of your vehice:"<<"\n";
cin>>tempNoPlate;
cout<<"Enter your Registration Number of your vehice:"<<"\n";
cin>>tempRegNumber;
setnoPlate_setRegNo_setOwner(tempNoPlate, tempRegNumber, tempOwnerName);
}
void display(){
displayInfo();
}
};
MAIN FUNCTION
int main(){
getInfo vehicleInfo;
vehicleInfo.get();
vehicleInfo.display();
return 0;
}
In void get() you are trying to get owner name in Registration number that is of int type, therefore it breaks
Secondly you Owner Name should be of string type other than Char since char can only store 1 character.
In class vehicle, noPlate is of int type, you must also take int type tempNoPlate in derived class get info
Here is the correct code
#include<iostream>
using namespace std;
class vehicle{
private:
int noPlate;
string owner;//Change in owner data type
int registrationNo;
public:
int modelNo;
void setnoPlate_setRegNo_setOwner( int number, int rNumber, string ownerName){ //Change in ownername data type
noPlate = number;
registrationNo = rNumber;
owner = ownerName;
}
void displayInfo(){
cout<<"***Vehicle Information Portal***";
cout<<" ----------- \n";
cout<<"Owner Name: "<<owner<<"\n";
cout<<"Registered Number Plate: "<<noPlate<<"\n";
cout<<"Registration Numaber: "<<registrationNo<<"\n";
}
};
class getInfo : public vehicle{
public:
void get(){
int tempNoPlate; //this should be of int type instead of char
int tempRegNumber;
string tempOwnerName; // change
cout<<"\n***Vehicle Registration Portal*** \n";
cout<<" ----------- \n";
cout<<"Enter your Registratered Owner name for your vehice:"<<"\n";
getline(cin, tempOwnerName); // change, GETLINE here is used to read space in name, you can use cin >> tempOwnerName but
// it wouldnt read space character.
cout<<"Enter your number plate of your vehice:"<<"\n";
cin>>tempNoPlate;
cout<<"Enter your Registration Number of your vehice:"<<"\n";
cin>>tempRegNumber;
setnoPlate_setRegNo_setOwner(tempNoPlate, tempRegNumber, tempOwnerName);
}
void display(){
displayInfo();
}
};
int main(){
getInfo vehicleInfo;
vehicleInfo.get();
vehicleInfo.display();
return 0;
}

strcpy is copying sth character onwards i string . How to resolve this error?

My complete code is at pastebin.
There is a train database , and user enters train number to book a ticket.The function updt_tick should copy the values of train's name,source and destination into passenger's reservation object.
But the problem is that 5th character onwards are only being copied.
Here is the function's code sample.Train database is entered by user.
void updt_tick()
{
fstream f;
f.open("train.dat",ios::in | ios::binary);
while(f.read((char*)&t,sizeof(t)))
{
if (tno==t.tno)
{
strcpy(bp,t.source);
strcpy(dest,t.dest);
strcpy(tname,t.tname);
amt=SeatNum*t.PerSeatFare;
break;
}
}
f.close();
}
The train class is ->
class train
{
public:
int tno;
char tname[100];
char source[100];
char dest[100];
int PerSeatFare;
public:
void getdetail();
void showdetail();
}t;
The reserv class is ->
`
class reserv
{
//Assume that cust select train according to his source and destination.
public:
int pnr;
int tno;
char tname[100];
char pnames[10][100];
int ages[10];
int SeatNum;
int i;
int d,m,y;
float amt;
char bp[100],dest[100];
void updt_tick()
{
fstream f;
f.open("train.dat",ios::in | ios::binary);
while(f.read((char*)&t,sizeof(t)))
{
if (tno==t.tno)
{
strcpy(bp,t.source);
strcpy(dest,t.dest);
strcpy(tname,t.tname);
amt=SeatNum*t.PerSeatFare;
break;
}
}
f.close();
}
public:
void getresdet()
{
cout<<"Enter the details as follows\n";
cout<<"Train no:";
cin>>tno;
cout<<"No of seats required:";
cin>>SeatNum;
cin.ignore();
for(i=0; i<SeatNum ; i++)
{
cout<<"Passenger name:";
gets(pnames[i]);
cout<<"Passenger age:";
cin>>ages[i];
cin.ignore();
}
cout<<"Date of travel:";
cin>>d>>m>>y;
cout<<"Details Accepted\n";
pnr=rand();
updt_tick();
}
void showresdet()
{
cout<<"Pnr no:"<<pnr;
cout<<"\nTrain no:"<<tno;
cout<<"\nTrain name:";
puts(tname);
cout<<"Boarding point:";
puts(bp);
cout<<"Destination pt:";
puts(dest);
cout<<"No of seats reserved:"<<SeatNum;
for(i=0; i<SeatNum; i++)
{
cout<<"Passenger name:";
puts(pnames[i]);
cout<<"Passenger age:"<<ages[i];
}
cout<<"\nDate of reservation:"<<d<<"-"<<m<<"-"<<y;
cout<<"\nYou must pay:"<<amt<<endl;
}
int getpnr()
{
return pnr;
}
};
Edit: There was nothing wrong with strcpy or any other code. I made
the foolish mistake of giving the file name as "train.dat" instead of
"trains.dat:.
Im not sure how did you manage to read 5 characters, because there is a problem is in your code. The file which you use to store train details is "trainS.dat", not "train.dat".

structure name not declared and swap function swaps without pass by refrence

I have this code,which takes input of 3 students from division a and b each.
those 2 divions are sorted and merged in a 3rd array according to birth dates of students.
the swap function ,I have not passed anything by refrence still its swapping and sort output is correct !!!.
NOTE:the line below #include..
void swap(struct a,struct b)
it should be
void swap(struct student a,struct student b)
but without changing that the program is runnong and giving correct outputs !! how ??
#include<iostream>
#include<string.h>
using namespace std;
void swap(struct a,struct b);
void findweek(struct student ar[10],int l,int bd1,int bm1);
struct student
{
//m is for month and b is for birthdate prn=prn number,name=name of student
int m,bd;
char prn[10],name[10];
};
int main()
{
//2 divisions a and b declared and will be merged into c
struct student a[3], b[3], c[6];
//division a input
for(int i=0;i<3;i++)
{
cout<<" Enter name of student "<<endl;
cin>>a[i].name;
cout<<"Enter prn no. "<<endl;
cin>>a[i].prn;
cout<<"Enter birth day "<<endl;
cin>>a[i].bd;
cout<<"Enter birth month "<<endl;
cin>>a[i].m;
}
//sorting of a
for(int i=0;i<3;i++)
{
for(int j=i;j<3;j++)
{
if(a[i].m>a[j].m)
{
swap(a[i],a[j]);
}
else if(a[i].m==a[j].m)
{
if(a[i].bd>a[j].bd)
{
swap(a[i],a[j]);
}
}
}
}
//division b input
for(int i=0;i<3;i++)
{
cout<<" Enter name of student "<<endl;
cin>>b[i].name;
cout<<"Enter prn no. "<<endl;
cin>>b[i].prn;
cout<<"Enter birth day "<<endl;
cin>>b[i].bd;
cout<<"Enter birth month "<<endl;
cin>>b[i].m;
}
//sorting of b
for(int i=0;i<3;i++)
{
for(int j=i;j<3;j++)
{
if(b[i].m>b[j].m)
{
swap(b[i],b[j]);
}
else if(b[i].m==b[j].m)
{
if(b[i].bd>b[j].bd)
{
swap(b[i],b[j]);
}
}
}
}
cout<<"-----------------------"<<endl;
cout<<"Division A"<<endl;
int count=0;
for(int i=0;i<3;i++)
{ //c has merged array , a being filled first
c[i]=a[i];
count++;
cout <<c[i].name<<"\t"<<c[i].prn<<"\t"<<c[i].bd<<"|"<<c[i].m<<endl;
}
cout<<"Division B"<<endl;
for(int i=0;i<3;i++)
{
//resume filling the array from count
c[count]=b[i];
cout <<c[count].name<<"\t"<<c[count].prn<<"\t"<<c[count].bd<<"|"<<c[count].m<<endl;
count++;
}
int bd1,bm1;
cout<<"Enter date to find birthdays in that week "<<endl;
cin>>bd1;
cout<<"Enter corresponding month "<<endl;
cin>>bm1;
findweek(c,count,bd1,bm1);
return 0;
}
//to swap the structure student arrays for sorting
void swap(struct student a,struct student b)
{
struct student t;
t=a;
a=b;
b=t;
}
void findweek(struct student ar[10],int l,int bd1,int bm1)
{
int count=0;
for(int i=0;i<l;i++)
{
int month_end=30;
int next_month=bm1+1;
//if(bd1>=23)
int end_date=bd1+7-month_end;
// else
int endofweek=bd1+7;
//l is length of ar , ar=copy of merged array, bd1&bm1 are date and month to search for birthday in that week
if((ar[i].m==bm1&&ar[i].bd>=bd1&&ar[i].bd<=endofweek)||ar[i].m==bm1+1&&ar[i].bd<=end_date)
{
if(month_end-bd1>7)
cout <<ar[i].name<<"\t"<<ar[i].prn<<"\t"<<ar[i].bd<<"|"<<ar[i].m<<endl;
else
{
if((ar[i].m==bm1&&ar[i].bd>=bd1)||(ar[i].m==next_month&&ar[i].bd<=end_date))
{
cout <<ar[i].name<<"\t"<<ar[i].prn<<"\t"<<ar[i].bd<<"|"<<ar[i].m<<endl;
}
}
count++;
if(count>7)
break;
}
}
}
It compiles even if you remove this line:
void swap(struct a,struct b);
Also, it compiles if you remove the whole swap function.
How is it?
Quite simple.
You are defining a function that takes two arguments: an incomplete type struct a and an incomplete type struct b.
That function is simply discarded from the overload set while searching the one to be used at function call.
Your main is not using your swap function. Instead, it's using the one from std:: namespace.
It is probably introduced by iostream or string, it's implementation defined.
Try changing the name of the function or putting a throw in your implementation of swap. In the second case, your runtime won't be affected.
Minimal, (not-)working example to reproduce the issue:
void f(struct s);
struct S {};
int main() { f(S{}); }
void f(S) {}
As you can see, the error is that you are referring to an incomplete type struct s.
swap is kinda of a somehow misleading example that compiles for the reasons above.
Reproducing an issue with a minimal example is often helpful.

Declaration terminated Incorrectly error in following code in cpp

Iam trying to develop C++ program for observer pattern but i am getting these errors.
Here's my CPP code , and i getting error continuously : "Declaration termination incorrectly" !
Thanks in Advance
Help me please i am desperate.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Subject{
public : virtual ~Subject();
virtual float attach()=0;
virtual int notify()=0;
};
class Observer{
public : virtual ~Observer();
virtual void update(int type, float amount, float bal)=0;
};
class Account : public Subject
{
public: float attach()
{
char name[12];
int account_no;
float bal;
cout<<"Enter the Name of Account Holder : ";
cin>>name;
cout<<"Enter the Account No. : ";
cin>>account_no;
cout<<"Enter the Balance of his account : ";
cin>>bal;
cout<<"The Name of Account Holder : "<<name;
cout<<"The Account No. : "<<account_no;
cout<<"The Balance of his account : "<<bal;
return bal;
}
int notify()
{
int type;
cout<<"\nMenu :\n\n1) Deposit\n2)Withdrawl\n";
cout<<"Enter the type for transition : \n";
cin>>type;
return type;
}
public: void update(int type, float amount, float bal)
{
char name[12];
int account_no;
if(type==1)
bal=bal+amount;
else if(type==2)
bal=bal-amount;
else
cout<<"Oops! Transition Type is invalild....";
cout<<"\nThe Details of Account Holder after Transition :-\n";
cout<<"The Name of Account Holder : "<<name;
cout<<"The Account No. : "<<account_no;
cout<<"The Balance of his account : "<<bal;
}
};
class obpt{
public : static void main()
{
Account ac;
//AccountUpdate au;
float balance, amt;
int type;
clrscr();
cout<<"\nWelcome To The Program of Observer Pattern of Account Transition\n";
cout<<"\nEnter the Details of Account Holder :-\n";
balance = ac.attach();
cout<<"\nCall notification for Deposit or Withdrawl Transition\n";
type=ac.notify();
cout<<"\nEnter the amount for transition : \n";
cin>>amt;
cout<<"\nAfter The transition the Main balance : \n";
ac.update(type, amt, balance);
getch();
}
}
You are missing a ; at the end of the class declaration. Correct:
class Foo
{
/*...*/
};
In C++, main should be a free function, the obpt class is wrong.
int main()
{
/* ... */
}
The error message you are receiving is coming from the compiler. It is stating that a declaration statement has not been ended correctly.
Somewhere in your code you are missing a semi-colon ; perhaps at the end of a class declaration or after a variable is defined.
Without seeing your code, there is no way for me to pinpoint the problem, but the error message should take you to the line if you double click it!
Regards, Rakesh.