-4

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;
}
  • 3
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Aug 28 '16 at 09:20
  • 2
    You pass `Books` by value to `func()`, meaning that `x` is *a copy* of the parameter. And it just updates the copy. – Bo Persson Aug 28 '16 at 09:25

1 Answers1

0

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++

Community
  • 1
  • 1
Shravan40
  • 8,922
  • 6
  • 28
  • 48