I have a class Film that contains an integer pointer Chapitres and the number of elements of that array Count_chapitres.
class film : public video
{
private:
int* Chapitres;
unsigned int Count_chapitres;
public:
film();
film(int* Chapitres, unsigned int Count_Chapitres, int Duree, string Name, string Filename);
virtual ~film();
void setChapitres (int * Chapitres, unsigned int Count_Chapitres);
int * getChapitres() const;
unsigned int getCountChapitres() const;
void printOut (ostream & Display) const;
};
The obvious problem is that giving away the pointer will break encapsulation.
1) I have tried setting the output of get to const int *, in which simply casting the output back using a const_cast reverted the measure back. As the following allowed the Evil pointer to externally change film data:
film* file2 = new film(Chaps, 3, 5, "hany", "daher");
file2->printOut(cout);
int * Evil = const_cast<int *>(file2->getChapitres());
*(Evil +1)=9;
file2->printOut(cout);
2) Also even though I put const int * as arguments for my constructor/setter it still takes int * objects as arguments in main making the const keyword essentially redundant.
The solution evidently does not lie in pointers to constant values. Any idea on how to proceed?
You need to understand that encapsulation is protection as in 'gun safety switch', not as in 'strong cryptography'. You should not worry about possibility of class users doing const_cast
with the returned const pointer
anymore than you would worry of them typing something like #define private public
before including your header class.
In C++ there are unlimited possibilities for deliberately breaking your encapsulation, both with outside behavior or without it. Instead, encapsulation tries to protect users of the class from innocent errors.
In your particular case, you need to const-qualify your getter function and return const int*
. Alternatively, since you already have trivial getters and setters, you can do away with them and simply declare your members public with the same level of encapsulation.