e.g:
int main()
{
class exampleClass{
public:
int x;
};
exampleClass one;
exampleClass two;
exampleClass three;
if (exampleClass manipulate_all x == 5)
{
// do something
}
return 0;
}
}
instead of:
int main()
{
class exampleClass{
public:
int x;
};
exampleClass one;
exampleClass two;
exampleClass three;
if (one.x == 5)||(two.x == 5)||(three.x == 5)
{
// do something
}
return 0;
}
Very new to c++, so apologies if this is a stupid question, or if this is far too advanced for a beginner.
I'm trying to create a collision system for my game, where each sprite has a class object, so I can check the player object against every other sprite. If this is a terrible idea please tell me.
If you want to have all members share a variable, you can use static variables
If they're part of a collision system you probably need a larger structure to hold all of the variables and just use a loop over that.
Alternatively, you could have a static variable as a list keep track of all other members of the class and loop over this, where the static variable is a vector of pointers to instantiated objects. This requires a lot more overhead for the individual class and its own function to modify all of the values.
Either way you'd have to write the container to hold all the values, but it's up to you on how you want to design it.
Modifying your class:
class exampleClass{
private:
static vector<exampleClass*> instances;
public:
exampleClass(){ instances.push_back(this);}
~exampleClass(){ /*Use some kind of id to find and erase the current instance from the list here.*/}
int x;
};
You can, if your member is a static member, but not if it's an instance member, like your case. But you also need to initialize a static member outside the class.
#include<iostream>
class exampleClass
{
public:
static int x;
};
int exampleClass::x = 0;
int main()
{
exampleClass one;
exampleClass two;
exampleClass three;
exampleClass::x = 5;
std::cout << one.x << two.x << three.x << std::endl;
return 0;
}
Related
Is there a way to access variables outside their class?
class MyClass1
{
public:
int x;
};
class MyClass2
{
public:
int get_x()
{
//somehow access MyClass1's variable x without
//passing it as an argument and return it.
}
}
int main()
{
MyClass1 obj1;
obj1.x = 5;
MyClass2 obj2;
std::cout << obj2.get_x();
return 0;
}
One of the main things making me reluctant to split my programs into many small organized classes rather than a few messy huge ones is the hassle of passing every single variable that one class might need from another. Being able to access variables without having to pass them (and having to update both declarations and definitions should something change) would be very convenient and would let me code more modually.
Any other solutions to my issue would also be appreciated, as I suspect there may be something dangerous about trying to access variable this way.
The only way you can get access to the x of MyClass1 is if you have an instance of that class, because x is not static.
class MyClass2
{
public:
MyClass2(MyClass1* c1) : myC1(c1) {}
int get_x()
{
return myC1->x;
}
private:
MyClass1* myC1;
}
Then you can use this like
int main()
{
MyClass1 obj1;
obj.x = 5;
MyClass2 obj2{&obj1};
std::cout << obj2.get_x();
return 0;
}
When we declare a member variable static, it is shared between all instances of the class. I've heard that you should think of the variable belonging to the class itself, not any instance. This lets us initialize the variable without instantiating any object of the class, which makes sense.
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
But why are we allowed to initialize a private static member?
class Something
{
private:
static int s_nValue;
};
int Something::s_nValue = 1;
Does private even mean anything when we are talking about static members?
Yes, it does mean something. Consider the following example, which throws a compiler error, because the member is private. Being able to initialize a private variable is not the same as being able to change it from any context.
class Something
{
private:
static int s_nValue;
};
int Something::s_nValue = 1;
int main(){
Something::s_nValue = 2; // Compiler error here.
}
Private still means the same thing: you cannot use the name Something::s_nValue except in the definition of a member of Something (or a friend, or a nested class within Something).
int Something::s_nValue = 1;
is the definition of a member of Something - namely, that static member s_nValue.
int Something::another_static_val = s_nValue; // also okay
int OtherClass::x = Something::s_nValue; // Illegal access!
int Something::getValue() const {
return s_nValue; // okay, getValue is a member of same class
}
int regularFunction() {
return Something::s_nValue; // Illegal access!
}
Does private even mean anything when we are talking about static members?
I'll try to answer with a classic example. Consider the following piece of code:
#include <iostream>
class foo {
static int count;
int id;
public:
foo() : id(++count) {}
int getid() const { return id; }
};
int foo::count = 0;
int main() {
foo f1, f2, f3;
std::cout << f1.getid() << std::endl;
std::cout << f2.getid() << std::endl;
std::cout << f3.getid() << std::endl;
}
LIVE DEMO
In the example above we use a private static int to count the instances of foo created. We made the count static member variable private because we don't want anyone else except object of type foo to mess with it.
And this is only a naive example, think of the possibilities.
Public, private and protected are properties of a class and not of an object. Their purpose is to let you specify which parts of this class are visible to other classes, and not to hide stuff from objects of the same class. So, you can write code like this :
class A
{
public:
bool operator<(const A& other)
{
return this->val < other.val;
}
private:
int val;
};
So, private makes sense even when applied to static members - it just says that other classes cannot see this member.
i have a variable map dataa ehich is used in three different class.i can define this variable globally and put all classes defination in one cpp file but i want to make different files for three different class and thus cant define it globally.
now i want to define this variable in one class say A and then want to use this dataa in the rest two class say B and C.
how can i do this.thanks for anyhelp in advance
You can use public get and set methods to access your variable in class A. Or simply create a public variable in class A.
You can use friends
class A
{
friend class B;
friend class C;
private:
int m_privateMember;
};
class B {
};
class C {
};
Now, B and C can access to A's private members.
But this is not the best way. Try to avoid it.
alternatively you can try to have this variable map data as part of a new singleton class. The rest of your 3 different classes can access this singleton class using get method
file: singleton.h
#include <iostream>
using namespace std;
class singletonClass
{
public:
singletonClass(){};
~singletonClass(){};
//prevent copying and assignment
singletonClass(singletonClass const &);
void operator=(singletonClass const &);
//use this to get instance of this class
static singletonClass* getInstance()
{
if (NULL == m_Singleton) //if this is the first time, new it!
m_Singleton = new singletonClass;
return m_Singleton;
}
int getData()
{
return data;
}
void setData(int input)
{
data = input;
}
private:
static singletonClass* m_Singleton; //ensure a single copy of this pointer
int data;
};
//declare static variable as NULL
singletonClass* singletonClass::m_Singleton = NULL;
File: ClassA.h
class ClassA
{
public:
ClassA(){};
~ClassA(){};
int getVarFromSingleton()
{
m_Singleton = singletonClass::getInstance(); //get a pointer to the singletonClass
return data = m_Singleton->getData(); //get data from singleton class and return this value
}
private:
singletonClass* m_Singleton; //declare a pointer to singletonClass
int data;
};
File: main.cpp
int main()
{
singletonClass* DataInstance;
ClassA a;
int data;
DataInstance = singletonClass::getInstance();
DataInstance->setData(5);
data = a.getVarFromSingleton();
cout << "shared data: " << data << endl;
return 0;
}
Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable.
I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.
class Myclass
{
public:
static int i;
};
int Myclass::i = 10;
class YourClass
{
public:
void doSomething()
{
Myclass::i = 10; //This is how you access static member variables
}
};
int main()
{
YourClass obj;
obj.doSomething();
return 0;
}
static is the right keyword here:
class A {
public:
static int i; // <-- this is a class variable
};
class B {
public:
void f() { A::i = 3; } // <-- this is how you access class variables
};
They only potential problem I can think of is that
You made the class variable protected or private, thus rendering it inaccessible from other code.
You forgot to specify the full scope of the class variable (with A:: in this example).
I think the Singleton Pattern would help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.
yes you can bro, try this
struct car{
string model;
string paint;
int price;
};
int main(){
// creates an object of the class car
car BMW;
// assign the values
bmw.model = "m sports";
bmw.paint ="red";
bmw.price = 24000;
}
This question already has answers here:
Can I access private members from outside the class without using friends?
(27 answers)
Closed 6 years ago.
I have a class A as mentioned below:-
class A{
int iData;
};
I neither want to create member function nor inherit the above class A nor change the specifier of iData.
My doubts:-
How to access iData of an object say obj1 which is an instance of class A?
How to change or manipulate the iData of an object obj1?
Note: Don't use friend.
Here's a way, not recommended though
class Weak {
private:
string name;
public:
void setName(const string& name) {
this->name = name;
}
string getName()const {
return this->name;
}
};
struct Hacker {
string name;
};
int main(int argc, char** argv) {
Weak w;
w.setName("Jon");
cout << w.getName() << endl;
Hacker *hackit = reinterpret_cast<Hacker *>(&w);
hackit->name = "Jack";
cout << w.getName() << endl;
}
Bad idea, don't do it ever - but here it is how it can be done:
int main()
{
A aObj;
int* ptr;
ptr = (int*)&aObj;
// MODIFY!
*ptr = 100;
}
You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:
NO you can't, atleast not in a portable way approved by the C++ standard.
The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.
If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
};
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
}
A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.
Modified Code Sample:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
friend void MytrustedFriend();
};
void MytrustedFriend()
{
MyClass obj;
obj.c = 10; //Allowed
}
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
//Call the friend function
MytrustedFriend();
return 0;
}
http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.
I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.
I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.
In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!
class A {
int iData;
};
int main ()
{
A a;
struct ATwin { int pubData; }; // define a twin class with public members
reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value
return 0;
}
There's no legitimate way you can do it.
Start making friends of class A. e.g.
void foo ();
class A{
int iData;
friend void foo ();
};
Edit:
If you can't change class A body then A::iData is not accessible with the given conditions in your question.
iData is a private member of the class. Now, the word private have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.
It's possible to access the private data of class directly in main and other's function...
here is a small code...
class GIFT
{
int i,j,k;
public:
void Fun()
{
cout<< i<<" "<< j<<" "<< k;
}
};
int main()
{
GIFT *obj=new GIFT(); // the value of i,j,k is 0
int *ptr=(int *)obj;
*ptr=10;
cout<<*ptr; // you also print value of I
ptr++;
*ptr=15;
cout<<*ptr; // you also print value of J
ptr++;
*ptr=20;
cout<<*ptr; // you also print value of K
obj->Fun();
}
friend is your friend.
class A{
friend void foo(A arg);
int iData;
};
void foo(A arg){
// can access a.iData here
}
If you're doing this regularly you should probably reconsider your design though.
access private members outside class ....only for study purpose ....
This program accepts all the below conditions
"I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."
//here member function is used only to input and output the private values ...
//void hack() is defined outside the class...
//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>
class A
{
private :int iData,x;
public: void get() //enter the values
{cout<<"Enter iData : ";
cin>>iData;cout<<"Enter x : ";cin>>x;}
void put() //displaying values
{cout<<endl<<"sum = "<<iData+x;}
};
void hack(); //hacking function
void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}
void hack() //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck; //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}