Calling functions from other classes - c++

I want to use a function from my Page class but I do not want to inherit from it. Is there another way I can use theonPage(vector<string> vec) function in my element and elementX class without using inheritance? Would association Work? I was thinking that.
Code is below:
class Page
{
string str;
vector<string>::iterator it;
void onPage(vector<string>vec);
};
class element
{
Page p;
};
class elementX : public element
{
};

Declare it public, so foreign classes can access it.
class Page
{
string str;
vector<string>::iterator it;
public:
void onPage(vector<string>vec);
};
(you can use public, private and protected to control access to class members, make sure to read them all up. private is the default for classes).

Yes you can. The issue I can see is that you did not declare the void onPage(vector<string>vec); function as public (place public: before the function), since class members are private (hidden for other classes) in C++ by default.

Related

Why can this member function access a private vector

Now I have here a code snippet that I am trying to understand. I thought that only friend functions could access private member variables, so why is the method 'grad' able to access 'a' here to get its size?
#include <vector>
using namespace std;
class Polynom{
private:
vector<double> a;
public:
Polynom(const vector<double>& v): a(v) {}
int grad() { return a.size()-1; }
};
int main()
{
return 0;
}
Ask yourself, if private member access disqualified the rest of the class from access, what would be the point of a private field? You declare a potentially complex object, and then literally can do nothing with it? You have a private region that can interact with itself, but which cannot have any effect on any public facing functionality? You use the private structures as middlemen to write to public fields that you then use? None of these scenarios makes that much sense. Access modifiers protect the class from external influences, but the OOP model assumes the programmer will take care of themselves within the class.
It is noteworthy that there is one condition in which private members can not be accessed: Inheritance. The base class private variables are there in a derived class, but cannot be referenced directly. To be clear,these are the base class' private variables. The child class has its own private scope that it can declare within and access normally.

Restrict pointer variable to class and sub-classes: Protected doesn't quite work

How can I ensure a variable (pointer) cannot be passed/accessed outside of a class?
I know the obvious answer is to make the variable private or protected but the code is part of an API and the class will be subclassed by users who can simply create a public get function to overcome that design.
class Component
{
public:
GUID gUid;
template<typename T>
T* addComponent()
{
T* cmp = new T();
auto res = components.emplace(cmp->gUid, cmp);
return cmp;
}
protected:
std::unordered_map<GUID, Component*> components;
};
class UpdaterComponent : public Component
{
public:
void init()
{
nCmp = addComponent<NetworkComponent>(); // ok to store and access component within class
}
// Not ok to expose sub components to outside
NetworkComponent* getNetworkComponent()
{
return nCmp;
}
private:
NetworkComponent* nCmp;
};
You mention, that the class it will be subclassed by users, and you are worried about get() functions, that will let them access the pointer.
In that case: make it private. That's what it for.
This will forbid inherited classes to access the pointer, too.
Access control protects against mistakes not malice.
They can simply copy/paste your header, insert a friend function into your class definition, include their copy of the header, then bypass your private or protected rules as they wish.
You can hide the layout of the struct behind a pImpl type pattern, but even then they can reverse engineer the layout and get access to it.
What you want to do cannot be done, barring support from the hardware/OS with encrypted memory.

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.

How to restrict part of public interface of a class to only one class?

Following is an interface:
class SIM{
private:
//private data
public:
Send();
Display();
Recieve();
Encrypt();
};
How do I restrict access to Display() function (it has to be lie in public part) of SIM to other classes except one class (Neo etc). I don't want to use friend etc.
Edit:
I can move the display() to private , how do i allow only NEO class to access it? 0_o
You can have Display take a dummy const reference to a type that can only be created from a privately nested within the class you want to be able to make the calls. Then in order to pass that type to Display you have to be a member of that class.
But why would you do that when friend does exactly what you want?
Code example:
class AllowedCaller
{
private:
class FriendHackHelp
{
};
public:
class FriendHack
{
public:
// You can only create a FriendHack from inside this class now...
FriendHack(const FriendHackHelp&) { }
};
void run();
};
class Displayer
{
public:
void Display(const AllowedCaller::FriendHack&) { /* Whatever */ }
};
void AllowedCaller::run()
{
Displayer d;
d.Display(FriendHack(FriendHackHelp()));
}
int main()
{
return 0;
}
In C++ this is simply not possible. What you could do is to pass the Neo class as a parameter to the Display() function as a reference and you would have a similar effect.
You can also split your SIM class to 2 classes: Displayable (with Display method) and SIM (with the remaining methods). Then, when creating Neo class, simply do not extend the Displayable class.
Let me ask you a question: What exactly is neo? Is it able to be inherited from SIM? If so, make Display() protected as opposed to private.
I've been wondering about this too in the past, check these questions:
programming language with granular method and property access
a way in c++ to hide a specific function
However,i come up to terms of the idea that the only way to implement this (in c++ at least) is to create multiple interfaces for each client class, and make each interface a friend of the client class that will access it
so you need to implement all and each of the interfaces with multiple inheritance

Can you have protected nested classes in C++?

I have a class that only really ever needed by classes in a certain class hierarchy. I wanted to know if it is possible to nest the class in the highest class's protected section and have all the other classes automatically inherit it?
"Inherit" is the wrong word to use since it has a very specific definition in C++ which you don't mean, but yes you can do that. This is legal:
class A {
protected:
class Nested { };
};
class B : public A {
private:
Nested n;
};
And code that is not in A or something that derives from A cannot access or instantiate A::Nested.