How can I Violate Encapsulation property? - c++

How can I Violate Encapsulation property without having a compile time error? (in C++)
just so curious..
This was actually a question asked by one of my professor.. Please don't misunderstand.
This was asked when we had a discussion over compiler error's

#define private public
#define protected public
#define class struct
There you go :-)

I'm going to assume that by "violating encapsulation" you mean "accessing private members from outside a class".
The only way to do this "legally" that I know is using friend classes / methods.
However, in order to use them you will need to modify the class which has private members - at which point it might be simpler to just redefine some methods from private to protected or public, depending on the case.

You don't get to*. Encapsulation is a feature of C++.
**unless you do something dark, evil, and magic.*

You change the headers defining the classes in question to make the desired members public. In other words, you remove the encapsulation. Don't do this.

Design a mirror class that has the same members as the class you are trying to access the nonpublic members of and hardcast an object of said class to the mirror class.
class original
{
private: int x,y,z;
public: int dosomething();
};
class mirror
{
public: int x,y,z;
};
int main()
{
original *o = new original;
mirror *m = (mirror*)o;
m->x = 10;
}
this of course is not guaranteed to work.

Related

C++ Classes Importance of Public and Private Domains

I'm fairly new to C++ and just recently learned about classes. When you define something in the private domain of a class, such as a class function, how exactly is it limited to that class? For example:
class Example {
void dosomething(param1, param2);
};
Would that mean that you can't access the class function in the main function? If so, what's the point of doing that, wouldn't that mean you can't use it at all?
One final thing, I've always seen class attributes defined under the private section of the class. What would happen if you put it under public?
Would that mean that you can't access the class function in the main function?
Yes.
If so, what's the point of doing that, wouldn't that mean you can't use it at all?
Of course you can use it. From within other functions of this class:
class Example {
void dosomething(int a, int b) {
std::cout << "dosomething(a=" << a << ",b=" << b <<")\n";
public:
void callDoSomething(int b) {
dosomething(13, b);
}
};
//main
Example e;
e.callDoSomething(5);
One final thing, I've always seen class attributes defined under the private section of the class. What would happen if you put it under public?
Nothing would happen. They would be visible to everyone (just like private vs. public functions) and anyone can access them.
In general, to keep encapsulation alright you want data members to be private, but it strongly depends on use case. I suggest getting some books on OOP and encapsulation to learn more about the topic.

Is Concept of Encapsulation Violated here?

#include<iostream>
class A {
public:
int a;
protected:
void func() {
std::cout<<"protected member"<<endl;
}
};
class B:public A
{
public:
using A::func; //Isn't this violation of encapsulation?
};
int main(){
B b;
b.func();
return 0;
}
Why the above code runs successfully?
Does it not violate the concept of Encapsulation?
Correct me if I am wrong.
This is an interesting question, and I think it highlights an important and often-overlooked aspect of encapsulation in c++.
My answer is that "yes, encapsulation has been violated, but not where you think". The actual violation was in declaring the method to be protected in the first place.
Your code demonstrates nicely the problem with the protected relationship with subclasses... they can de-protect you with ease. Another way of saying this is that if you're going to make a member protected, you may as well make it public because in reality protected is public if your subclasses want it to be.
What does this mean in practice?
It means that if you make a member function protected, it is forever part of your class's interface. Therefore you must treat is as seriously as you would any other public member function and indeed as if it were a public member function.
Which is to say that it should be as stateless as possible, with as few preconditions as possible and should you change the implementation, the logical effect on the object as a whole must remain unchanged.
The example that you are showing is not a violation of encapsulation, because subclasses are allowed to add public members on top of what they inherit, and they also are allowed to access protected members that they inherit.
In your case, B, a subclass of A, decided to add a new member function called func, whose implementation happens to consist of a single invocation of A::func.
Generally, protected members should be regarded part of interface of your class, along with its public members. Despite the fact that their visibility is limited to subclasses, protected members are not part of the class implementation, because any change to protected members naming or semantics need to be coordinated with changes to all subclasses of the class.

How to "hide" a virtual method? (C++)

there is a post with a quite similar title here, but as I understood the actual problem there is different.
I would like to know if it is possible to force a user of a class i wrote to override a certain method but at the same time it should not be possible to call this method (but its only called from within my class).
For example, if I want to do the following:
class AbstrDataSource {
private:
int index;
protected:
int currentData;
public:
int getData(){return currentData;}
void loadData(int i){
// check valid index here
if (index != i){doLoad(i);}
this->index = i;
}
virtual void doLoad(int i)=0;
};
In loadData() I can check that the index is in a valid range and do some bookkeeping, while the actual loading has to be supplied by the user via overriding doLoad(). Because pure virtual methods are part of the interface, they are public, but how do I force the implementation of doLoad() to be visible only to my own class?
My idea was to hide the object in some wrapper:
class DataSupplier {
public:
DataSupplier(AbstrDataSource* s) : source(s){}
void loadData(int i){source->loadData(i);}
int getData(){return source->getData();}
private:
AbstrDataSource* source;
};
And instead of using the abstract class I use the wrapper:
int SomeCalculation(DataSupplier* a,DataSupplier* b){
return a->getData() + b->getData();
}
However, this does not really help. Lets say a second person provides a implementation of my abstract class:
class ImplDataSource : public AbstrDataSource{
public:
void doLoad(int i){this->currentData = i;}
};
Then a third person still has access to doLoad():
void main(){
AbstrDataSource* ads = new ImplDataSource();
DataSupplier* ds1 = new DataSupplier(ads);
DataSupplier* ds2 = new DataSupplier(ads);
ads->doLoad(10); // <- How to avoid this ??
ds1->loadData(12);
ds2->loadData(12);
SomeCalculations(ds1,ds2);
}
Maybe there is a way to achieve this by using access specifiers...?
EDIT: I already got some helpful answers, but I think I did not state my question clear enough. As long as ImplDataSource declares doLoad() as protected or private, everything is fine. However, looking only at AbstrDataSource, there is no hint that any implementation of doLoad() should be private (even if the abstract doLoad was protected or private the actual implementation can have any access). I would like to know if it is possible to somehow "enforce" any implementation of the abstract doLoad() to be private. Maybe I am just thinking too complicated and the easiest way would be to add a comment to the documentation of the abstract method ("implement as private or it may fail").
What you're trying to achieve is called the template method pattern and
I think the best you can do here is to delegate to the doLoad method the less "sensitive" behavior and put the loadData (and the part you wanna hide from the derived class) in private access
Make the method doLoad() protected, then it can only be called from within the superclass, and it overloads (and hides) the pure virtual method of the base class.

Accessing base class private members in C++

I have not used C++ for a really (really) long time and this question may be stupid but I could really use some help.
If my base class has a private data member and my derived class is derived publicly, the private members of the base class are NOT inherited. But, they can still be accessed via the inherited public functions. Eg:
class B{
int a,b;
public:
void SetA(int);
int GetA();
};
class D:public B{
public:
SetAAttribute(int x)
{ SetA(x); }
}
Now, my question is as follows:
Technically, the derived class objects do not have the 'a' attribute defined on them. In layman terms, I am basically setting an attribute on an entity when the attributes does not even exist in the first place. It seems unintuitive to imagine such a concept. Did I understand this correctly?
Any extra explanation or correction would be greatly appreciated.
It's not that the attribute doesn't exist anymore, it's just that it's hidden from you. The base class methods can still access the base class members because they're not hidden from each other.
The private base members are inherited, the compiler will just give you an error if you try to access them, since you aren't supposed to access them directly.

Doxygen ignoring inherited functions, when class inherits privately but the functions declared public again

Sorry for long winded title, this makes a lot more sense with an example.
Suppose we have a class A:
class A {
public:
void someFunction();
void someOtherFunction();
};
And another class that privately inherits from A. However, we re-declare one of the inherited functions as public:
class B : private A {
public:
A::someFunction;
}
When this code is processed by Doxygen, it does not recognise the public declaration of someFunction in class B. Instead, it shows someFunction as a privately inherited function. This is incorrect.
Is anybody aware of how to fix this?
Cheers
I can't comment so I'll post this as an answer.
When you do private inheritance in C++, it's a variant of composition or agregation. It's like a "Car - has an - Engine" relationship, so maybe Doxygen has a problem with this syntactic way of doing things. You could probably turn this around a bit to get a good public inheritance or a real composition.
If you want to know more about private and protected inheritance : http://www.parashift.com/c++-faq-lite/private-inheritance.html
Hope it helps !