Constructor calling problem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
// Program to calculate fine using class.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class library
{
long bookid;
char bookname[25];
int fine;
int no_of_days;
float calculate()
{
float tot_fine;
if((fine*no_of_days)<2000)
{
tot_fine=fine*no_of_days;
}
else if((fine*no_of_days)>=2000)
{
tot_fine=1.05*fine*no_of_days;
}
return tot_fine;
}
public:
library()
{
bookid=0;
strcpy(bookname,"Not defined");
fine=0;
no_of_days=0;
}
library(int num,char bname)
{
bookid=num;
strcpy(bookname,bname");
fine=0;
no_of_days=0;
}
void getdata()
{
cout<<"Enter book ID: ";
cin>>bookid;
cout<<"Enter book name: ";
gets(bookname);
cout<<"Enter fine per day: ";
cin>>fine;
cout<<"Enter number of days: ";
cin>>no_of_days;
}
void showdata()
{
cout<<"\nBook ID: "<<bookid;
cout<<"\nBook name: "<<bookname;
cout<<"\nFine per day: "<<fine;
cout<<"\nNumber of days: "<<no_of_days;
cout<<"\nTotal fine: "<<calculate()<<"\n\n";
}
};
|
In the above program, how do I call the diff. constructors in main?
Thanks in advance.
The constructor will be automatically selected depending on the arguments you pass during object construction.
But how to do that?? Can you please write that part of the code?
1 2 3 4
|
int main ()
{ library l1; // calls default constructor
library l2 (1,'A'); // Calls explicit constructor
}
|
A couple of comments:
Line 35, you probably want bname to be a string or a character array, not a single character as you have it.
Line 38, you have an extraneous ".
thanks for the help
and so to call the functions using these constructors, can i do the following:
1 2
|
l1.showdata();
l2.showdata();
|
Sure.
Topic archived. No new replies allowed.