am i doing this right? (classes)

My code compiles right but i wanted to know if i built it correctly. Also thats how i access private variables right? by creating a constructor?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CLASS
{
    public:
        void Function();
        void Function2();
        CLASS()
        {
            seven = 7;
            six = 6;
        }
    private:
        int seven;
        int six;
};
Any class member function can access private members of its class.
yes but in my program there is a function that adds six and seven together, so what i want to know is did i create it right so that the variables can be used outside of the class?
No, private variables can not be accessed outside its class. You should write either member functions that return its values or references to them or declare in the class some friend functions.

For example you could write a member function Add which will do what your want.

For example

1
2
3
4
5
6
7
8
9
class CLASS
{
    public:
// your definitions are skipped for simplicity
   int Add() const { return ( seven + six ); }
    private:
        int seven;
        int six;
};
Last edited on
You can access six and seven from any function within CLASS. i.e. Function and Function2 can access six and seven.

did i create it right so that the variables can be used outside of the class
six and seven are declared private so they are not visible outside of CLASS.

If Function is supposed to return the sum of six and seven, then you probably want to declare it as follows:
1
2
int Function ()
{ return six + seven; }
ok but i dont want the function to add six and seven in the class i want it to do it outside of the class, which it already does and works. so what i want to know is am i doing it properly? the variables six and seven are in the class, there nowhere else in the program. The only thing that function2 does is output them to the screen. Here is my full code.

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
36
37
38
39
40
41
#include <iostream>

using namespace std;

class CLASS
{
    public:
        void Function();
        void Function2();
        CLASS()
        {
            seven = 7;
            six = 6;
        }
    private:
        int seven;
        int six;
};

int main()
{

    CLASS ClsObj;
    ClsObj.Function();

    cout << "\n";

    CLASS ClsObj2;
    ClsObj2.Function2();
}

void CLASS::Function()
{
    cout << "this is inside a function" << endl;
}

void CLASS::Function2()
{
    cout << six + seven << endl;
}
Topic archived. No new replies allowed.