Why I can't get access to a private function?

I've written a simple class given below. I had set the values through setab() function but the add()function didn't work. Compiler shows CPP/class.cpp|20|error: ‘int Calc::add()’ is private|

What is the reason?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

using namespace std;

class Calc
{
    int a, b;
    int add();

public:
    void setab(int num1, int num2);
};

void Calc::setab(int num1, int num2)
{
    a=num1;
    b=num2;
}

int Calc::add()
{
    return a+b;
}


int main ()
{
    Calc sum;

    sum.setab(5,6);

    cout<<sum.add()<<endl;

    return 0;
}
Last edited on
by default everything inside the class body is private if you want it to be public you have to add the public access specifier.
1
2
3
4
5
6
7
class Calc
{
    int a, b;
    public:
        int add();
        void setab(int num1, int num2);
};
Last edited on
Thank you..I think I know it.
But is it not possible to get access into a private function?
Isn't there any way?
you cant access private functions from outside the class
Ow..ok..thank you. :)
But is it not possible to get access into a private function?
Isn't there any way?
Use friend. Read this:
http://www.cplusplus.com/doc/tutorial/inheritance/
Topic archived. No new replies allowed.