Accessing private data members using friend class [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I learnt that declaring a class as a friend class enables it to use the contents or members of the class in which it is declared. I used the following code:
#include <iostream>
using namespace std;
class two; // forward class declaration
class one {
private:
friend class two; // friend class declared
int a; // to be accessed later
public:
one() { a = 5; }
};
class two {
private:
int b;
public:
two() {
b = a; // intended to access 'a' and assign to 'b'
cout << " " << b << endl;
}
};
int main() {
one one_obj;
two two_obj;
return 0;
}
Error is: 'a' was not declared in this scope
What I've noticed in most examples of friend class is that constructor 'two()' will use 'class one' as the argument and later use the data member 'a'. But I wouldn't always want to make a new object as an argument to constructor two(). For example, calling constructor one() has already been done and the value of 'a' has already been set. Making a new object would mean doing that again, which might not be favorable. So what it all leads to is that, can I access members of class using friend class but without having to declare an object once again?

Class two being a friend of class one only overrides the access checking.
It still means you must actually refer to a static member of the class, or a non-static member of a specific instance of the class the normal way.
You might profit from choosing a tutorial or book from The definitive C++ book list, and reading up about it all.

b = a; // intended to access 'a' and assign to 'b'
Just because it is friend you cannot directly access it's members. You need to create one object to access it's members.
one o;
b = o.a; //now it should work

Related

C++ Access "parents" class members [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm new into learning C++.
And what I've learned is that using global var is not a good practise.
And I don't wanna use static var, since they behave like "global" var as well, if I'm correct.
In the code below I want class B to get access to its "parents" member, is that possible?(see class B constructor)
Or how should I approach this, where I want to access var/members between classes?
Friends, seems not to be the way either.
class A {
public:
int number_I_want = 987;
A() {
B* classB = new B();
}
};
class B {
public:
int nr = 0;
B() {
nr = this->parent->numer_I_want; /// Here I wanna access the "parent" A's member with value 987
cout << nr * nr;
}
};
int main() {
A* classA = new A();
return 0;
}
Class A is The parent class so if the members/fields are not private . you can access them in class B. But the class B must Be the child of class A. You have to extend class b from A. And if you have parametrized constructor of parent class you must initialize classA constructor from class B
In C++, there is no parent\child relation for object. Sometimes it gets confusing with people coming from languages with object memory model (which are either VM-based or interpreters). Parent there is an object owning this one. C++ uses abstract memory model. If a class Bis inherited from other class A, class A is abase class of B. Base class and class members are subobjects of given class, meaning their storage is part of enclosing object's storage. Consecutively base class's members are subobjects too and are accessible as class members with consideration of access level and inheritance level (private, public, protected).
Enclosing object owns included ones and call to its destructor results in their destruction.
If you need actual parent\child relation , you have to implement it and pass a pointer (?) to parent into child's constructor, while it have to be able to register self within given parent.
Some C++ framework emulate object model by using metaprogramming technique, e.g. Qt Framework's QObject may have a parent and list of children.
Using pointer to >>this<< keyword when creating a "child" class worked for me.
class A {
public:
int nr;
A();
};
class B {
public:
B(A* classA) {
std::cout << "Written in class B, value from class A: "<< classA->nr;
};
};
A::A() {
nr = 77;
B* classB = new B(this);
delete classB;
}
int main() {
A* classA = new A();
delete classA;
return 0;
}

What is better practice? Pass class member by pointer or identifier? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Let's say I have a class, and I want another class or function to read on its members. (For example, UI reading a player's scores and other things.)
Let's say I have this happening a lot, with many different variables, over a long period of time.
Do I, A, pass it by a pointer to the other class so it can read from memory...
class VariableReader {
public:
int* read;
void GiveYourVariableToMe(int* var) {
read = var; // keep accessing the variable with this "read" member
};
};
or Do I, B, create an array of objects and an object identifier for it to use
std::map<std::string, int> VariablesToRead;
class VariableReader {
public:
std::string identity;
void GiveYourVariableToMe(std::string Identifier) {
VariablesToRead[identity]; // keep accessing this variable with the through the map
};
};
Or is there something else I should do?
EDIT: Maybe I didn't explain it well enough.
I'm talking about if I had a class with a bunch of member variables and I want the variable that it reads from to be object specific, like:
class Player {
public:
int var1;
int var2;
int var3;
int var4;
int var5;
int var6;
int var7;
};
and I create, let's say a bunch of text objects that when updated, display the variable assigned to them
void Game() {
TextObject obj1; // displays var1 when updated
TextObject obj2; // displays var2 when updated
TextObject obj3; // displays var3 when updated
TextObject obj4; // displays var4 when updated
TextObject obj5; // displays var5 when updated
// ...
}
Usually, you want to avoid either of these. If another class, such as some class X, needs to read the value of some thing owned or known to class B, usually you provide some member function of B that provides the value, with a name such as GetFoo. For example, some function XF in X will have an object b of type B. Maybe it was passed by reference, or the function in X constructed it, whatever. To get the value of Foo from b, XF will use b.GetFoo(). The GetFoo function will look like:
class B
{
private:
Some declaration of Foo;
…
public:
TypeOfFoo GetFoo() { return Foo; }
};
This is preferable to providing XF some pointer to the Foo in b because it means class B is free to change how it manages Foo. Foo could be a dynamically allocated object whose address changes at times, or it could be a value that is computed rather than stored directly. And, once you let X have a pointer to Foo, then the implementation of B cannot change so that Foo is a different type or is otherwise managed differently unless all the code in X and other uses of Foo changes. Generally, you want to avoid any classes outside B having much information about what is inside B. They should not know the types or locations of B’s internal data.
Supposing you have decided that class X must have some way of accessing Foo, then letting it have a pointer to a const Foo is likely better than the map and string version you propose. That causes run-time lookups of names, which is just wasteful if the names are known at compile time. Even so, with a const pointer to Foo being made available, you need to carefully document the obligations and behaviors of the classes. Once a b object has allowed some other class to have a pointer to Foo, b cannot let the address of Foo change, and b must not be destroyed unless the holders of pointers to its Foo are done using it. These sorts of interlocking relationships are prone to errors and should be avoided.
Stick with giving X a GetFoo() function in B until you have very good reason to do something different. If you need to select from multiple values to be obtained, then GetFoo(identifier) is okay, where identifier is an integer or enum, and GetFoo looks up the object in an array.
I am not sure I understand your question but I think what you want to do is to pass an instance of one class to another class
class Player
{
public:
// your "variables"
int32_t Score() {.. }
};
class UI
{
public:
void ShowScores(const Player& player)
{
std::cout << player.Score();
}
};

how did the variables get memory without creating the object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
#include<iostream>
using namespace std;
class A
{
private:
int a,b;
public:
void setdata(int x,int y){
a=x;b=y;
}
void show_data(){
cout<<a<<b;
}
};
class B: public A{
};
main(){
B b1;
b1.setdata(3,4);
b1.show_data();
}
How does setdata work even if we don't create an object of class A (how did the variables a and b get memory)? And how was it possible to access the private variables of A using an object b1 of class B? I am surprised to see my program working properly.
How does setdata work even if we don't create an object of class A (how did the variables a and b get memory)
But the code does create an object of class A, right here:
B b1;
Since B is derived from A, each object of type B contains an object (the base class subobject) of type A.
How was it possible to access the private variables of A using an object b1 of class B
Yes, the object is of type B, but the function actually doing the access (setdata) is a member of class A, and thus has a member's access rights to all of class A.
That's how inheritance is supposed to work: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/inher.htm
In short, you've created an object of type B and you've declared that class B inherits from class A. That means that an object of type B is also of type A, just more specific. The same way a float is a number, while an integer is also a number. A Dog is an Animal, while a Cat is also an Animal.
When you define
class B: public A
{
};
that means that class B should inherit all public methods from class A. setdatais a public method, as is show_data()

Initialize private access variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
InC++, is it valid to initialize a private access variable outside of the class definition like this?
class Test
{
private: int a;
public: int b;
}
int Test::a = 1;
The example in your question is not valid. If the member variable is static you can initialize it like you do in your example. If the member variable is not static you should initialize in in either the constructor or class definition.
It also does not matter what the access privilege is and the variables are initialized the same way regardless if they are public, protected, or private .
struct Foo
{
Foo() : a{1} // ctor-initializer
{
b = 2; // ctor body
}
int a;
int b;
int c = 3; // At definition.
};
"is it valid to initialize a private access variable ... like this?"
No. If you want to initialize that variable for each instance of Test, do it in a constructor.
class Test
{
Test() : a{1} {}
private: int a;
public: int b;
}
If you want all the instances of your class Test share the variable a, you can make it static. Il you do, you can initialize it like you said.

Pass Object to Class via Constructor [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Why does this code not work:
int main () {
Bob bob;
bob.giveANewFredSomeData();
Fred::sharedFred.getANumber(); //Crashes here due to someData inside fred being NULL
return 0;
}
Class Data {
int aNumber;
}
Class Bob {
void giveANewFredSomeData{
Data data;
Fred::sharedFred = new Fred(data);
}
}
Class Fred {
Data someData;
static sharedFred;
Fred (Data data) {
someData = data;
}
int getANumber(){
return someData.aNumber
}
}
Your code is not working because:
You need a semicolon after the declaration of a class
static is not a valid type
static objects have to be initialized outside of their definition in the class in order to be used elsewhere in the code. You need something like: Fred Fred::sharedFred; before main
Declaration of a function must have () in front of the function name before the {} braces
the classes have to be in the scope of main function for them to be used, and also in the scope of each other depending on what is calling what. i.e. main has to be declared after the class and same for each class that calls another
Properties/methods declared in a class are private by default. To make group of properties/methods public, have the keyword public followed by a colon at the top of the group