Please anyone help me on classes. I have written this class example and keep getting error on that the function is private. I though variables in functions are private but mmh, I think I'm wrong.

Can anyone clarify how to rectify this? Also, could you explain to this New Bee how to make honey of CLASSES' using keyword PRIVATE and PUBLIC? (Make function visible yet the Local variables to function invisible)

thanks alot

Recommended Answers

All 4 Replies

Post your code because my eyes aren't good enough to see what's on your monitor.

#include <iostream>

using namespace std;

class Math{
    int Addition(int a, int b)
        {
            int r = a+b;
            return (r);
            }

    int substract(int a, int b)
        {
            int r = a-b;
            return(r);
            }
    };


int main()
{
    Math Steve;
    int z ;
    z = Steve.Addition(1, 9);
    cout<<"Good! Answer is"<< z<<endl;
    return 0;
}

In classes everything is declared private by default. You have to explicitly use the keywords public or protected, and it's fine to explicitly use the keyword private as well.

#include <iostream>
using namespace std;

class Math
{
    private:  //this line can be removed without detriment to the program, but there can be no doubt, even to a beginner, when it's there. 
        int x, y;
    
    public:
      Math(int a, int b) : x(a), y(b) {}
      int Addition(){return x + y;}
      int Substract(){return x - y;}
};

int main()
{
    Math Steve(1, 9);
    cout << "addition is " << Steve.Addition() << endl;
    cout << "subtraction is " << Steve.Subtraction() << endl;
    return 0;
}

Once a Math object is declared by passing two arguments to the non-default constructor the internal variables of the Math object cannot be changed or access from anything outside the class other than a friend.

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.