Is it possible to change the class attribute at run-time in C++ language.For example as below :
class base
{
public:
//public members
private :
//private members
};
class derived1 : attribute base
{
public:
//public members
base::<base method name> //so that it an be made accessible from the main - outside the class.
private:
//private members
};
can the attribute-public,private,protected be changed at runtime, dynamically?
Rgds,
softy
You cannot change the access modifiers of a class. End of story.
Disclaimer: There are hacks for just about everything, including this. Don’t use them.
Based on your comments in the question when asked why you want this, it looks like what you’re trying to do is control access to a class’ run-time properties based on its other run-time properties. For example, maybe a
Character‘sPowersare only accessible ifCharacter‘sLevelis >= 42.This is not a technical question about the mechanics of C++ syntax, but a business logic question. You’ll find the answer to this question in the design of your program and its algorithms — not some technical C++ trick.
Classes are often used to model things. In your case, a character in a game. Maybe this character has a level and a list of powers (which I’ll represent simply as
strings).In that case:
…is a simplistic representation of your character model. Now, if you want to control access to
powers_at run-time based on the value oflevel_, you can use an accessor method:Now you can only get to the character’s powers if the character is of sufficiently high level.
This is still a highly simplistic example, and the above code is not production quality. However, the idea is there — when implementing your program’s business logic, your focus should be on the algorithms you write much more than the technicalities of C++, or whatever language you’re using.