In the following code, how do I change the line under

cout << "\nThe value of bogus in num1 is " << num1.bogus;

to get it to compile correctly. I know its calling for theValue which is private. Not sure what to change to make it work:

#include <iostream>
using namespace std;

// Class Definition for the MyInt class
class MyInt
{
    private:
       int theValue;
       
    public:
       MyInt( );
       MyInt( int );

       void setValue( int );
       int getValue ( );
       float reciprocal( );

       int bogus;     // a public data member
};

// The class implementation for the MyInt class
// Constructors
MyInt::MyInt( )
{
    theValue = 0;
    bogus = 5;
    
}

MyInt::MyInt( int n )
{
    theValue = n;
    bogus = 3;
}

// Getters and setters
void MyInt::setValue( int n )
{
    theValue = n;
}

int MyInt::getValue( )
{
    return theValue;
}

// Calculation functions
float MyInt::reciprocal( )
{
    return 1.0 / theValue;
}

// The Driver
int main ( )
{
    // Test the Constructors
    /* 1 */   MyInt num1;
    /* 2 */   MyInt num2( 2 );

    /* 3 */   cout << "\nThe value of bogus in num1 is " << num1.bogus;
            cout << "\nThe value of theValue in num1 is " << num1.theValue;

    // Test setter
    /* 4 */   num1.setValue( 5 );
    /* 5 */   cout << "\nnum1's new value = " << num1.getValue( );

    // Test reciprocal
    /* 6 */   cout << "\nnum2's reciprocal = " << num2.reciprocal( );

    cout << "\nTest complete ... hit Enter to exit.";

    system("PAUSE");
                return 0;
}

Recommended Answers

All 4 Replies

Just change it to

cout << "\nThe value of theValue in num1 is " << num1.getValue(); 
// The get and set public functions are provided to access private variables

Hmm After I added the () I get:

wksht.cpp:9: error: `int MyInt::theValue' is private
wksht.cpp:62: error: within this context
wksht.cpp:62: error: `num1.MyInt::theValue' cannot be used as a function

I didn't just append a () only. I changed what is before the () also. Look more closely.

Ahh thanks. I was thinking I had to keep theValue variable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.