user2276948
user2276948

Reputation: 1

C++ bool coding help needed

I am trying to write a code (object oriented programming) based on the requirements below however my bool kept returning a true whereas it should be false. Hope you guys can advise me on what went wrong with my code.


REQUIREMENTS

Member(string = "xxx", bool = false, string = "addr")
Constructor with default values

setMember(string, bool, string): void
Set the values of data members to the respective pass-in values

setPremium(bool): void
Set the value of data member, premium to the pass-in value

getPremium():bool
Returns the value of data member, premium

setMember(string, bool, string): void
Set the values of data members to the respective pass-in values

displayMember():void
Uses cout to display the data members

MY CODE

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

class Member
{
private:
    string name;
    bool premium;
    string address;
public:
    Member(string = "xxx", bool = false, string = "addr");

    void setMember(string, bool, string);
    void setPremium(bool);
    bool getPremium();
    int index;

    void DisplayMember();
};

Member::Member(string name, bool premium, string address)
{
    this-> name = name;
    this-> premium = premium;
    this-> address = address;
}

void Member::setMember(string name, bool premium, string address)
{
    this-> name = name;
    this-> premium = premium;
    this-> address = address;
}

void Member::setPremium(bool)
{
    int i;
    bool premium;
    i = 0;

while (i != 4)
{
    i = i + 1;
}
    if (premium >= 4) 
    {

    index = i;
        premium = true;
    }
    else 
        premium = false;
}

bool Member::getPremium()
{
    return premium;
}

void Member::DisplayMember()
{
    cout<<"Name : "<<name<<endl;
    cout<<"Premium : "<<boolalpha<<premium<<endl;
    cout<<"Address : "<<address<<endl;
}

int main()
{
    Member detail1("Martin ", "2 Tampines Avenue");
    detail1.DisplayMember();

    cin.ignore();
    cin.ignore();
}

Upvotes: 0

Views: 520

Answers (2)

Ming
Ming

Reputation: 4300

To fix your problem, simply change the order of constructor's arguments.

public:
    Member(string = "xxx", string = "addr", bool = false);

And:

Member::Member(string name, string address, bool premium)
{
    this-> name = name;
    this-> premium = premium;
    this-> address = address;
}

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318698

Your local bool premium is shadowing the member variable. To write to the latter you need to use this->premium or rename the local variable. Besides that, the setPremium code makes pretty much no sense - for example you are using integer operations on a boolean.

This is how setPremium should be implemented:

void Member::setPremium(bool premium)
{
    this->premium = premium;
}

Additionally you are using undefined variables such as boolalpha. Your code shouldn't even compile...

Upvotes: 2

Related Questions