Bong Meister Bong Meister - 3 months ago 11
C++ Question

How to return a value back to main using accessor and object with array

The below code works just fine except for the last bit (last 2 cout), the compiler doesn't return the value as it should, both the if statements doesn't compute and return appropriate value. Where did I do wrong, how can I rectify this? I use Codeblock.

#include <iostream>
#include <iomanip>
using namespace std;

class Books
{
private:
string isbnNo, title, author;
float price, discountedprice, discountperc;
public:
void set_Data();
void calcDiscountedPrice();
float getDiscountedPrice();
};
void Books :: set_Data()
{
cout<<"\nEnter ISBN : ";
getline(cin, isbnNo);
cout<<"Enter Title : ";
getline(cin, title);
cout<<"Enter Author's name : ";
getline(cin, author);
cout<<"Enter price : ";
cin>>price;
cout<<"Enter discount (%) : ";
cin>>discountperc;
cin.ignore();
}
void Books :: calcDiscountedPrice()
{
discountperc/=100;
discountedprice=price*discountperc;
discountedprice=price-discountedprice;
}
float Books :: getDiscountedPrice()
{
return discountedprice;
}
void func(Books x)
{
x.set_Data();
x.calcDiscountedPrice();
}
int main()
{
Books B1;
cout<<"Enter data for new incoming book this Month......"<<endl;
func(B1);
Books B2[5];
cout<<"Now we shall enter and display data for 5 special books...."<<endl;
float a=0;
int b=0;
for(int i=0; i<5; i++)
{
func(B2[i]);
if(B2[i].getDiscountedPrice()>a)
{
a=B2[i].getDiscountedPrice();
}
if(B2[i].getDiscountedPrice()<30)
{
b++;
}
}
cout<<"\n--------------------------------------------------------"<<endl;
cout<<"The most expensive book is RM "<<a<<endl;
cout<<"The number of books that are below RM 30 are : "<<b<<endl;

return 0;
}

Answer

You are passing Books by value to func().

void func(Books x)
{
    x.set_Data();
    x.calcDiscountedPrice();
}

This strategy is known as pass by value. It just of copy not actual object.

You need to pass Books by reference into func. For more details please refer How to pass objects to functions in C++