Having trouble accessing variable - variables

I want to find the address of one of the structure's data members, but I'm having trouble accessing its variables. Is there of a solution that donesn't require me to change the struct in any way?
h file
class C
{
private:
int x;
char b;
};
cpp file.
char *p2 = new char[128];
memset(p2,'aa',128);
Test_C *r2 = new(p2) Test_C[3];
//inside for loop
printf("Address: 0x%x, Value of b: %x \n",&r2[i]->b, r[i].r=0x50);
I'm getting the error at &r2[i]->b;
Also some code review would be nice :) I'm planing on outputting values of the C struct with padding

It seems you have posted a C++ class and not a C struct.
From here:
private members of a class are accessible only from within other
members of the same class or from their friends.
So, to answer your question, you cannot access those private members from outside the class without modifying the class itself (to include public accessors, for instance).

Related

Comparison operator overloading for class in D?

I am currently learning D and struggling to understand how operator overloading could work for a class? Overriding opCmp makes sense and works correctly for a struct, but for a class it requires taking the right hand side as a Object instead of as my type.
This means I can't access any members to do a comparison. What's the point in the overload then? Am I missing something?
Sure you can access your members:
class MyClass {
int member;
override int opCmp(Object other) {
if (auto mcOther = cast(MyClass)other) {
// other, and thus mcOther, is an instance of MyClass.
// So we can access its members normally:
return member < mcOther.member ? -1
: member > mcOther.member ? 1
: 0;
} else {
// other is not a MyClass, so we give up:
assert(0, "Can't compare MyClass with just anything!");
}
}
}
The reason opCmp for classes takes Object as a parameter is it's being introduced in the Object class, from which every D class derives. Introducing opCmp there was a sensible choice back in the day, but less so now. However, since we don't want to break every piece of D code out there that uses opCmp (and opEquals, toHash and toString) with classes, we're kinda stuck with that choice.

What is 'Access specifier' in Object Oriented Programming

What is 'Access specifier' in Object oriented programming ?
I have searched for it's definition several times but not get the satisfactory answer.
Can anyone please explain it to me with realistic example ?....
Thanks in advance
What are they?
This wikipedia article pretty much sums it up. But Let's elaborate on a few main points. It starts out saying:
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.1
So an Access Specifier aka Access Modifier takes certain class, method, or variable and decides what other classes are allowed to use them. The most common Access Specifiers are Public, Protected, and Private. What these mean can vary depending on what language you are in, but I'm going to use C++ as an example since that's what the article uses.
Accessor Method | Who Can Call It
-----------------------------------------------------------------------
Private | Only the class who created it
Protected | The class who created it and derived classes that "inherit" from this class
Public | Everyone can call it
Why is this important?
A big part of OOP programming is Encapsulation. Access Specifiers allow Encapsulation. Encapsulation lets you choose and pick what classes get access to which parts of the program and a tool to help you modularize your program and separate out the functionality. Encapsulation can make debugging a lot easier. If a variable is returning an unexpected value and you know the variable is private, then you know that only the class that created it is affecting the values, so the issue is internal. Also, it stops other programmers from accidentally changing a variable that can unintentionally disrupt the whole class.
Simple Example
Looking at the example code from the article we see Struct B i added the public in there for clarity:
struct B { // default access modifier inside struct is public
public:
void set_n(int v) { n = v; }
void f() { cout << "B::f" << endl; }
protected:
int m, n; // B::m, B::n are protected
private:
int x;
};
This is what would happen if you created an inherited struct C that would try and use members from struct B
//struct C is going to inherit from struct B
struct C :: B {
public:
void set_m(int v) {m = v} // m is protected, but since C inherits from B
// it is allowed to access m.
void set_x(int v) (x = v) // Error X is a private member of B and
// therefore C can't change it.
};
This is what would happen if my main program where to try and access these members.
int main(){
//Create Struct
B structB;
C structC;
structB.set_n(0); // Good Since set_n is public
structB.f(); // Good Since f() is public
structB.m = 0; // Error because m is a protected member of Struct B
// and the main program does not "inherit" from struct B"
structB.x = 0; // Error because x is a private member of Struct B
structC.set_n() // Inheritied public function from C, Still Good
structC.set_m() // Still Good
structC.m = 0 // Error Main class can't access m because it's protected.
structC.x = 0; // Error still private.
return 0;
}
I could add another example using inheritance. Let me know if you need additional explanation.

Should C++/CLI data members be handles or values?

I'm new to C++/CLI and I'm wondering what is "best practice" regarding managed type data members. Declaring as handle:
public ref class A {
public:
A() : myList(gcnew List<int>()) {}
private:
List<int>^ myList;
};
or as a value:
public ref class B {
private:
List<int> myList;
};
Can't seem to find definitive advice on this.
When writing managed C++ code, I'm in favor of following the conventions used by the other managed languages. Therefore, I'd go with handles for class-level data members, and only use values (stack semantics) where you'd use a using statement in C#.
If your class member is a value, then replacing the object entirely means that the object would need a copy constructor defined, and not many .NET classes do. Also, if you want to pass the object to another method, you'll need to use the % operator to convert from List<int> to List<int>^. (Not a big deal to type %, but easy to forget, and the compiler error just says it can't convert List<int> to List<int>^.)
//Example of the `%` operator
void CSharpMethodThatDoesSomethingWithAList(List<int>^ list) { }
List<int> valueList;
CSharpMethodThatDoesSomethingWithAList(%valueList);
List<int>^ handleList = gcnew List<int>();
CSharpMethodThatDoesSomethingWithAList(handleList);
It all depends on the lifetime. When you have a private member which lives exactly as long as the owning class, the second form is preferable.
Personally, I would use the second form. I say this because I use frameworks that are written by other teams of people, and they use this form.
I believe this is because it is cleaner, uses less space, and is easier for the non-author to read. I try to keep in mind that the most concise code, while still being readable by someone with minimal knowledge of the project is best.
Also, I have not encountered any problems with the latter example in terms of readability across header files, methods, classes, or data files ...etc
Though I'm FAR from an expert in the matter, that is what I prefer. Makes more sense to me.
class AlgoCompSelector : public TSelector {
public :
AlgoCompSelector( TTree *tree = 0 );
virtual ~AlgoCompSelector(){ /* */ };
virtual void Init(TTree *tree);
virtual void SlaveBegin(TTree *tree);
virtual Bool_t Process(Long64_t entry);
virtual void Terminate();
virtual Int_t Version() const { return 1; }
void setAlgo( Int_t idx, const Char_t *name, TTree* part2, TTree* part3 );
void setPTthres( Float_t val );
void setEthres( Float_t val );
private:
std::string mAlgoName[2]; // use this for the axis labels and/or legend labels.
TTree *mPart1;
TTree *mPart2[2], *mPart3[2]; // pointers to TTrees of the various parts
TBranch *mPhotonBranch[2]; // Used branches
TClonesArray *mPhotonArray[2]; // To point to the array in the tree
for example

Storing MyClass values in List

I am completely new to C++\CLI and I have the following problem: I have a class called, for example, MyClass, a few values of which I need to store in memory. I have decided to use List, because it is the most familiar to me, since I was using C# for a long time. So here goes the code:
//Header File
ref class MyClass
{
public:
MyClass(void);
private:
System::Collections::Generic::List<MyClass^> values;
};
//CPP file
MyClass::MyClass(void){
this->values=gcnew System::Collections::Generic::List<MyClass^>();
}
The compiler keeps on saying that there's an error C2582. But if there's no assignment operator, then how should I initialize the List?
Thanks in advance.
values should not be a List<...^>, but a List<...^>^. You want to assign a reference, not to create another clone of the list.

using static c variables in Objective C classes

i have helper C functions in some Objective C classes.
Just found out that the values of global, static C variables which i use in these functions are shared between instances of the class (duh), which is not what i want.
Is there a way to declare these variables local to instances of the class, so that they are visible by the helper functions without passing them explicitly?
Is there a way to declare these variables local to instances of the class
Sure, make them instance variables.
But:
so that they are visible by the helper functions without passing them explicitly?
You can pass the object into the function. If you have appropriate accessors, the function can get them. And if you have mutators, it can modify them, too.
But if you're doing that, you might as well just create a method, and automatically have access to the instance variables.
want to avoid method calls where necessary
logically separate it so your low level code is in c or c++, then add the required data to your objc class:
/* c example */
typedef struct t_generator {
UInt32 a;
} t_generator;
static void Generate(t_generator* const gen) {
/.../
}
#interface MONObjCGeneratorContainer : NSObject
{
t_generator generator;
NSString * name;
UInt32 b;
}
#end
if the data interface is as simple you can just access them from the instance:
- (void)method { GenerateB(&b); }
that should meet all the requirements you have posted (so far).