c++ access main objects from other file - c++

I wonder how it is possible to access an object that was created in the main function from another class.
main.cpp
#include"ClassA.h";
#include"ClassB.h";
int main()
{
ClassA objectA;
return 0;
}
ClassA.h
#pragma once
class ClassA
{
public:
ClassA():_privateVar(100)
{};
~ClassA()
{};
//Getters
float getPrivateVarA(){ return _privateVarA; };
//Setters
void setPrivateVarA(float privateVarA){ _privateVarA = privateVarA; };
private:
//Just a value
float _privateVarA;
};
ClassB.h
#pragma once
class ClassB
{
public:
ClassB():_privateVarB(50)
{ };
~ClassB()
{ };
//This is what i´m trying to achieve: Acces objectA
// like this: objectA.getPrivateVarA(); or objectA.setPrivateVarA;
int getPrivateVarB(){return _privateVarB;};
private:
int _privateVarB;
};
I've been all week searching for an answer to this and found nothing...
If anyone knows of some books or have any information on how I can get there would be grateful.
Thank you.

You placed your question in the middle of the ClassB declaration. You can't execute code there. Whatever you do must be done from within a function.
A function in ClassB can be defined so that it accepts a reference or pointer to a ClassA. Then that reference can be used to call getPrivateVarA().
In other words, if class B needs to access a class A then it is up to your code to initialize B with the required reference. This can be done when creating the B object, or when calling a method of the B object.

objectA has function-local scope within main(). By definition, objects can be directly accessed only within their visible scope. That's what C++ is all about.
Of course, if you pass a reference or a pointer to this object, to some other function, that other function can access the instantiated object indirectly, via the pointer or the reference.

I can't say with 100% certainty that you can't, but you definitely should not be doing that. If you want to use an object created in a different scope then you need to pass it into the scope you want to access it from either by value, reference or via a pointer.
First Class A:
class A {
public:
ClassA() : _privateVar(100) {}
~ClassA() {}
float getPrivateVarA() { return _privateVar; }
void setPrivateVarA(float val) { _privateVar = val; }
private:
float _privateVar;
};
First Class B:
class B {
public:
ClassB() : _privateVar(50) {}
~ClassB() {}
// by copy
float getPrivateVarB_byCopy(ClassA a) {
return _privateVar + a.getPrivateVarA();
}
// by reference
float getPrivateVarB_byRef(ClassA &a) {
return _privateVar + a.getPrivateVarA();
}
// by pointer
float getPrivateVarB_byPointer(ClassA *a) {
return _privateVar + a->getPrivateVarA();
}
float setPrivateVarB(float val) { _privateVar = val; }
private:
float _privateVar;
};
Now for main.
int main(void) {
ClassB b;
ClassA a; // for copy and ref
ClassA *a2 = new ClassA(); // for pointer
b.getPrivateVarB_byCopy(a); // => 150
b.getPrivateVarB_byRef(a); // => 150
b.getPrivateVarB_byPointer(a2); // => 150
delete a2; // clean up pointer
return 0;
}
Although your example this type of access is really not a good idea, not sure why you'd want to go about doing things this way.

Related

Calling a method inside a method of a different class C++

In my code, I have two classes. The first class has a private variable x. I'm trying to change its value by calling a method defined in a second class - setClass1X(). This method takes two parameters, the value that I want to set x to and an object of type class1. This method should call another method setX() of an object given as a parameter and pass it the value that i want to set x to. Then that method setX(), defined in the first class should set the value of x for that particular object. At the end program calls a function getX() from the first class and prints its return value. I always get 0 as an output because that is what constructor sets the value of x to, meaning that this approach does not work. Can you spot a mistake or tell my why this approach does not work. Thanks!
#include<iostream>
using namespace std;
class class1
{
private:
int x;
public:
class1()
{
x=0;
}
int getX()
{
return x;
}
void setX(int a)
{
x=a;
}
};
class class2
{
public:
void setClass1X(int n, class1 c)
{
c.setX(n);
}
};
int main()
{
class1 c1;
class2 c2;
c2.setClass1X(5, c1);
cout << c1.getX();
return 0;
}
As #MikeCAT has already pointed out a copy of class1 being pass and the changes made to the copy doesnt reflect into the original instance. So the solution is to pass the instance by reference.
However classes should be dependned on each other at the class level rather than at method level to mark clear dependnecy; unless you there is specific reason for not doing this.
class class2
{
private:
class1& c1;
public:
class2(class1& c)
: c1(c)
{
}
void setClass1X(int n)
{
c1.setX(n);
}
};
int main()
{
class1 c1;
class2 c2(c1);
c2.setClass1X(5);
cout << c1.getX();
return 0;
}
In Your setClass1X function, a copy of an object is passed to c1, so modification to that won't affect caller.
To have your functions modify what is passed, you should use references.
void setClass1X(int n, class1& c) // add "&"
{
c.setX(n);
}

Can a C++ class function tell whether the class member reference to an outside class has been updated since last call?

Say I have two classes:
class A:
class A
{
private:
int _i;
public:
A(int i){_i=i;}
void update(int t){_i=t;}
friend class B;
};
class B:
class B
{
private:
A &_a;
public:
void respond();
B(A &);
};
B::B(A & a)
:_a(a)
{}
void
B::respond()
{
/*
if (a._i has been updated after last call of B::respond)
{
do something
}
else
{
do nothing
}
*/
}
Is there anyway to achieve the task described in B::respond() in C++/C++11? What about _i is replaced by an pointer and B::respond() needs to respond to the content of a pointer?
Note that I can't modify class A.
There are two ways to achieve this:
Save the value of a._i in the B::respond() function and compare against that value in the next B::respond() call.
Set some internal flag when calling A::update. When calling B::respond(), check for that flag and unset it.
There is no way to directly see if a member has been accessed or updated, but there are indirect techniques. You could do something as simple as having a bool _i_updated; in class A. Then, inside of the A::update(int) function, simply set _i_updated = true; every single time the function is called. B::respond could check if _a._i_updated { and then set _i_updated = false every time it finds it to be true.
You could keep the value of member variable A::_i as member of class B:
class B
{
private:
A &_a;
int _i;
public:
void respond();
B(A &);
};
B::B(A & a)
:_a(a), _i(a.i)
{}
And consequently:
void
B::respond()
{
if (_i != a._i) {
// do something
}
else
{
// do nothing
}
_i = a._i;
}

how to set internals of a class

Hi I am pretty new to C++ and im converting C code to C++. I started by converting all the structs to classes, and added accessors and mutators for the internals, but some structs have other structs inside them. I want to know the best method for setting the internals of a class within a class, such as
struct1.struct2.struct3.i = 5;
where i is an int. Should I be passing as reference using accessors? but seeing as accessors tend to be const would this be something I should do?
something like
class1.get_class2().get_class3().set_i(5) or something if it can be done in this kind of format.
This is probably a dumb question but i have no idea how to do it, Thank You
class1.get_class2().get_class3().set_i(5)
is possible if get_class2() is non-const and returns a non-const pointer reference.
However, this approach completely breaks the encapsulation. The users of class1 should not (and must not) know that class1 uses class2 inside and that in turn uses class3 inside.
If a setter-API is absolutely necessary, then a better approach is do it hierarchically. For example
// User
class1.set_i( 5 );
// class1
class1::set_i( int x ) { class2_obj.set_i( x ); }
// class2
class2::set_i( int x ) { class3_obj.set_i( x ); }
// class3
class3::set_i( int x ) { i_ = x; }
I am not so sure about that ... did you put a class inside a class or an object inside a class ?
something like :
class OBJ1
{
//methods , and other stuff
}
class OBJ2
{
public OBJ1 *O ;
}
is valid , so you can acces a method like :
OBJ2 *N2 ;
N2->O->some_method();
however , something like
class OBJ2
{
class OBJ1;
}
is not valid :P
again... not sure if this is exactly what you asked ...
If you really have a good reason to access your member object via getters and setters, you can do the following:
class A {
public:
void f() const {}
};
class B {
public:
const A &get_a() const {
// the returned reference will be read-only, i.e. only non-const member
// functions can be called, and public members can not be written.
// it needs to be stored in a const A & object.
return a;
}
A &get_writable_a() {
return a;
}
void set_a(A &a) {
//make sure that the assignment operator of A will take care of all the
//dirty internals, such as internal buffers that need to be deleted.
this->a = a;
}
private:
//the member
A a;
};
int main() {
B b;
b.get_a().f();
}
If you don't have a good reason to do so, I'd recommend to simply make it a public member, and access it directy:
class A {
public:
void f() const {}
};
class B {
public:
A a;
};
int main() {
B b;
b.a.f();
}
Isn't that simply much more elegant?
Note that you can use friend to specify other functions or classes that are allowed to directly access your private members.
As was also pointed out in an other answer, in most cases it is a bad idea to make a member object visible to the outside at all.

c++ Creating vector of function pointers in a given class, with function being a member of a different class

I am having a vector of function pointers in one class and to it i want to pass address of function in some other class. The following implementation gives errors. What is the correct way?
class A
{
public:
void func ()
{
}
};
class B
{
public:
std::vector<void(*)()) myVec;
void update_func()
{
myVec.push_back(&A::func);
}
};
int main()
{
B* b = new B;
b->update_func();
return 0;
}
A pointer to the non-static member function A::func doesn't have type void(*)(void), it has type void(A::*)(void). So either change the vector to match the elements that you want it to have, or else use a pointer to a function of the correct type for the vector.
A's func() has to be static to match the declaration of the function pointer. Meanwhile, it needs to be public such that it is accessible to class B.
update_func() in B also needs to be public since otherwise in main it is not accessible.
vector declaration has typo, it has to be vector<>, not vector<).
//
class A
{
public:
static void func ()
{
}
};
class B
{
std::vector<void(*)()> myVec;
public void update_func()
{
myVec.push_back(&A::func);
}
};
int main()
{
B* b = new B;
b->update_func();
return 0;
}
This code has many issues..
first b->func should have () after it if you want to call that function..
second.. what is void update func().. also bad code..
third you cannot use these functions since they are private...
you do however push it correctly into the vector...

How to pass a linc to class function and call it?

So I have a class like
class mySafeData
{
public:
void Set( int i )
{
myMutex.lock();
myData = i;
myMutex.unlock();
}
void Get( int& i)
{
myMutex.lock();
i = myData;
myMutex.unlock();
}
private:
int myData;
boost::mutex myMutex;
};
its instance is running. Lets call instance A. I want to create a new class that would take as a start up argument some kind of link to Getter from A and would be capable to somehow save link to thet getter for calling it inside its private methods vhen needed. how to do such thing?
Sounds like you want something like this:
class myOtherData
{
public:
myOtherData(mySafeData& dataSource) :
myDataSource(&dataSource)
{}
private:
// note that if you take the advice in the comments,
// you don't need this wrapper function at all,
// it's simple just to call myDataSource.Get()
int GetData()
{
int result;
myDataSource.Get(result);
return result;
}
mySafeData* myDataSource;
};
mySafeData a;
myOtherData b(a);
// b uses a as its data source (make sure it lives as long!)
I'm not sure what you mean by linc/link. Are you asking for anything more than this pattern?
class Foo {
public:
Foo(mySafeData& d) : data(d) {}
int someFunction() {
int i;
data.get(i);
return i;
}
private:
mySafeData& data;
};
...
Foo f(a);
What's wrong with pointers? Smart, Shared, Scoped... I'll use standard pointers for now.
class B
{
public:
B(mySafeData* ptr) // constructor takes a memory pointer as parameter
:SafeData_ptr(ptr)
{
SafeData_ptr->foo(); // call public function from class A
}
~B() // destructor
{
}
private:
mySafeData* SafeData_ptr; // will hold the mem address of instance A when
// this class is initialized
};
Later on your code, when you have instance A ready, you would do something like this:
B b_demo(&A); // &A passes the memory address of the instantiated object
// and A::foo() will be automatically called when B is constructed.
This is probably not the smartest way to do it, but I think it illustrates the idea.