A question about private data type?

Hi.
Using private data type is not clear for me, for example I want to make a class, it has some private variables in it so as to I can control the users if they are under 18 years can not access my private variable variables by using access specifiers, I know, how it is done, but say for example I don't use private variables in stead I use some if-else statements instead of private variables, so what's the difference?
Private members are only accessible to member functions of that class. The compiler enforces this. If you want only some users to access some data then that's something you'll have to control with code of your own:

1
2
3
4
5
6
7
8
9
10
class Stuff {
private:
    std::string naughtyBits;
    unsigned age;
public:
    string getNaughtyBits() {
        if (age<18) throw "you're too young";
        else return naughtyBits;
    }
};
So for that example you provided above, what happen if I make age public?
I can control the users if they are under 18 years can not access my private variable variables

Ok, there are good chances I’m misunderstanding your example, so forgive me if I’m telling you things you already know.

Private variables inside classes, commonly referred to as ‘properties’, are not intended not to be accessed by the program user, but the program developer.
Example:
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
#include <iostream>
#include <string>

class MyClass {
public:
    std::string public_variable = "I am a public variable";
private:
    std::string private_variable = "I am a private variable";
};

int main()
{
    MyClass myinstance;
    // This function could have been written by a different person from the
    // one who wrote the class MyClass.
    // MyClass author decided he agreed to let 'public_variable' being
    // freely modified, but wanted private_variable to be inaccessible.
    std::cout << "public_variable is declared 'public': it means I "
                 "can modify it directly:\n"
              << "public_variable now is '" << myinstance.public_variable << "'\n";
    myinstance.public_variable = "Now I have been modified";
    std::cout << "And now is '" << myinstance.public_variable << "'\n";
    
    // But I cannot easily modify private_variable.
    // If you uncomment the following line and try to compie this code, you'll 
    // get a compilation error.
    //myinstance.private_variable = "I'm inaccessible!!";
    return 0;
}

Last edited on
Thank you. I got it.
Topic archived. No new replies allowed.