Access static const in another class. - c++

A static const variable declared and defined in a class. How to access it in the private access of another class in same project. Is it possible?
//in some header file
Class A{
public:
//some data
private:
static const uint8_t AVar =1;
//other data
};
//in some another header file
Class B{
static const Bvar;
};
//here inside Class B it possible to give Bvar = AVar ? If yes, How ?

A clean way to avoid duplication of the magic value without weakening encapsulation of either class is to move the magic value to a different place that is publicly accessible to both classes.
For example:
namespace detail {
enum MAGIC_NUMBER_T {
MAGIC_NUMBER = 1
};
}
class A{
private:
static const uint8_t AVar = detail::MAGIC_NUMBER;
};
class B{
static const uint8_t BVar = detail::MAGIC_NUMBER;
};

Related

How to effectively use explicit argument names to clear up "magic numbers" in this polymorphic context

I have this code:
class Base
{
public:
Base(int attributeA, int attributeB, int attributeC) : attributeA_(attributeA),
attributeB_(attributeB), attributeC_(attributeC) {}
private:
int attributeA_;
int attributeB_;
int attributeC_;
}
And then I have a couple child classes like this
class ChildA : public Base
{
public:
ChildA() : Base(1, 2, 3) {} // magic values
}
class ChildB : public Base
{
public:
ChildB() : Base(4, 1, 7) {} // magic values
}
t's hard for me to remember what arguments go in what order (they aren't actually called A B C so when I see Base(4, 1, 7), I might say "What is 1 doing already?". A solution I came up with is the following:
class ChildA : public Base
{
public:
ChildA() : Base(attributeA, attributeB, attributeC) {} // no magic values
private:
static constexpr int attributeA = 1;
static constexpr int attributeB = 2;
static constexpr int attributeC = 3;
}
class ChildB : public Base
{
public:
ChildB() : Base(attributeA, attributeB, attributeC) {} // no magic values
private:
static constexpr int attributeA = 4;
static constexpr int attributeB = 1;
static constexpr int attributeC = 7;
}
And now it's crystal clear that when I see 1 in ChildB's call the Base, I know it will be set to attributeB. I'm unsure this is a great solution because ChildA and B already have access to the protected values of Base attributeA_ and so forth as well as the private static declarations. This means that from the child classes we have two different variables to access the same value.
Since these variables are only used once, I was thinking on just putting them in the header file. Such as
child_b.h:
static constexpr int attributeA = 4;
static constexpr int attributeB = 1;
static constexpr int attributeC = 7;
class ChildB : public Base
{
public:
ChildB() : Base(attributeA, attributeB, attributeC) {}
}
That way, ChildB can only access the attributeB with the protected variable from Base attributeB_. This solution works fine for one child class, but if I do this for multiple header files and include them there's redefinition conflicts (since they have the same name). Is there a good way for me to have these argument hints without having the data accessible twice inside of the class? I guess I could do the second solution and use static constexpr int childBattributeB = 1. Alternatively, perhaps my concern is not that bad and I should just roll with my first solution. Thoughts?

Dont allow access to member variable directly within same class

I am not sure is my question is right or not? But let me still try to ask once.
I have a Class with have few member variables defined. As per OO concepts, every member function can access , all member variables of its class.
But I want these member variable to be accessed via specific methods (Lets say Getters) , even within same class member functions.
It there any way to do it?
class A {
public:
void func1();
void func2();
B getB();
private:
B b;
}
void A::func1() {
b.functionFromB(); // function uses member variable b directly
}
void A::func2() {
B b1=getB(); // function ask for B from a function and then uses it. // I need something like this... And ensure each function uses same way otherwise there should be warning...
b1.functionFromB();
}
Thanks,
Kailas
No, there is not. You can do it via encapsulation and inheritance like:
class shape
{
private:
int angles;
protected:
shape(int angles_):angles(angles_){};
int getAngles() const;
}
class square : private shape
{
public:
square():shape(4){}
void doSth()
{
\\ you can access angles only via getAngles();
}
}
Any private members of the class can be accessed from within the class, but not by users of the class. So it looks like you need private members and public methods that allow access to them.
class A
{
private:
int a;
public:
int getA() {return a;}
};
int main()
{
A inst;
int t;
inst.a =5; // error member a is private
t = inst.getA(); //OK
}
The concept extends fine to nested class declarations in case you only want to allow instance of a class to be created from another class; details here
As others have said - you have to add an additional layer.
If you want to give access to specific methods then you can use the friend keyword. E.g.
// Public.h
#pragma once
class Public
{
public:
Public();
int GetI() const;
float GetF() const;
private:
std::unique_ptr<Private> p_;
};
//Public.cpp
#include "Public.h"
Public::Public()
: p_(new Private)
{
}
int Public::GetI() const
{
return p_->i_;
}
float Public::GetF() const
{
return p_->f_;
}
// Private.h
#pragma once
class Private
{
friend int Public::GetI() const;
friend float Public::GetF() const;
int i_;
float f_;
};
Keep in mind that every friend method can access ALL private members.
If you really really want to limit which methods can access which members then you can wrap each member in a separate class/struct and make only the getter/setter of that member a friend of that class/struct but I would not recommend this approach.

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

Reaching static variables in C++

If I define a static variable in classA:
static int m_val;
and initialize like
int classA::m_val = 0;
Can I use directly m_val as it is in order to access it in ClassA (or any other class) or should I use it like classA::m_val.
Inside of ClassA, just write m_val. Outside of ClassA, ClassA::m_val.
However, m_val is not const in your example, so it (typically) should be private anyway. In that case, you'd not access it directly from other classes but provide a member function to retrieve a copy:
class ClassA
{
private:
static int m_val;
// ...
public:
static int GetVal();
};
Implementation:
int ClassA::m_val = 0;
int ClassA::GetVal()
{
return m_val;
}

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