views:

206

answers:

5

Variables "protected" are prone to be malicious changed by derived class? Should I use "private" in base class variables instead of "protected"?

+10  A: 

If you're worried about 'malicious' modifications, then even marking data as private: will not help.

The C++ access specifiers are only useful for code that's essentially playing by the rules.

Marking a member as private will prevent normal users of your class from messing with them. However, even non-malicious code that has bugs can corrupt those members. Overruns, buggy pointer arithmetic or improper use of casts lets a C++ programmer cause these problems.

Michael Burr
+1  A: 

Well, protected members do get inherited. If you don't want that to happen, make them private.

Eduard - Gabriel Munteanu
+2  A: 

"Malicious" access can't be prevented in C++, because you can always get around the compiler restrictions somehow. If you're worried about "accidental" changes, go ahead and make it private.

Mark Ransom
A: 

Take a look at: http://www.parashift.com/c++-faq-lite/private-inheritance.html#faq-24.5

You probably want private.

cbrulak
A: 

In general, if you're contemplating declaring a private variable, you should step back and ask yourself why are you even publishing the declaration in the header file?

instead of exposing your member variables for all the world to see in foo.h:

class foo {
private:
    int    please_dont_modify_me;
    double pretend_you_dont_see_this_declaration;
    char   dont_look_at_this [128];
public:
    ....
};

just use an incomplete private type, that is not defined:

class foo {
    struct foo_privates & mine;   // incomplete type
public:
    ...
};

then in foo.cpp ONLY:

struct foo_privates {
     int    i;
     double d;
     char   str[128];
};

Of course, the constructor for foo has to allocate the separate object and the destructor has to destroy it.

Die in Sente