How access class variables in c++ - c++

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;
}

Related

C++ declaring a static object in a class

I'm trying to declare a static object of a class A that I wrote in a different class B, like this:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
What I want to achieve is to get int x in B::start() to equal int x in class A (4).
I tried googling all this for the past hour and all I understood was that C++ doesn't allow static objects' declarations. Is that correct?
If so, here's my question. How can I get the same result? What are my available workarounds? Keeping in mind that the rest of my code depends on the functions in class B to be static.
Error
error LNK2001: unresolved external symbol "private: static class A B::obj1"
Thanks!
You should initialize static var, the code:
class A // just an example
{
int x;
public:
A(){ x = 4; }
int getX() { return x; }
};
class B
{
static A obj1; // <- Problem happens here
public:
static void start();
};
A B::obj1; // init static var
int main()
{
B::start();
}
void B::start()
{
int x = obj1.getX();
}
As thinkerou said, you need to include the declaration of the variable:
A B::obj1;
For normal, non-static member variables you don't need this step because the variables are declared behind the scenes as part of the constructor. These variables are then tied to the instance of the class you just constructed. But static variables are not tied to any instance of a class; they are shared by all instances of a class. So constructors can't properly deal with them.
C++ gets around this by making you manually declare (and optionally initialize) any static member variables. Depending on where they are declared, they typically get constructed before your main() function starts, so they are available for use immediately.

Accessing private variables through levels of classes.

So in my current understanding of how to use encapsulation correctly it is a good rule of thumb to make variables private and access them through member functions of the class like this:
class Aclass{
private:
int avar;
public:
void ch_avar(int val){avar = val};
int get_avar() {return avar;}
};
My question is how would I access a private member of a class instance which is its self a private member of another class. Here is an example of the way I have been trying to do it (not retyping the example above for brevity)
class LargerClass{
private:
int other_var;
Aclass A; //has two instances of class "Aclass"
Aclass B;
public:
void ch_other_var(int val){other_var = val;}
int get_other_var() {return other_var;}
// this is the important line for the question
int get_avar(Aclass X){return X.get_avar();}
};
Now In my real program there are a few more levels of this and I keep getting the compilation error that "Aclass" is an unknown type. Even though I have included the header file for Aclass in the Larger class. Since I am stuck I thought It would be good to find out if this is even the correct (or an acceptable way) of doing what I want. I am new to OOP and this feels sloppy to me.
To access the private member of a class instance which is its self a private member of another class, can be done this way. You don't need to pass a Aclass X. It is unneccessary. You can call it by the instance name you have given..
class LargerClass{
private:
int other_var;
Aclass A; //has two instances of class "Aclass"
Aclass B;
public:
void ch_other_var(int val){other_var = val;}
int get_other_var() {return other_var;}
// this is the important line for the question
int get_avar_A(){return A.get_avar();}
};
If you have 20 instances of Aclass, rather you create a vector of Aclass instances.
class LargerClass{
private:
int other_var;
Aclass A[20];
public:
void ch_other_var(int val){other_var = val;}
int get_other_var() {return other_var;}
// this is the important line for the question
int[] get_avar_A()
{
int other_var[20];
for(int i= 0; i<20; i++)
{
other_var[i] = A[i].get_avar();
}
return other_var;
}
};

Private static class members

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.

accesing a class variable in other class function C++

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;
}

How to access private data members outside the class without making "friend"s? [duplicate]

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.....";
}