I want to change a variable member of class B, in a method member of class A.
Example:
A.h:
class A
{
//several other things
void flagchange();
}
A.cpp:
void A::flagchange()
{
if (human) Bobj.flag=1;
}
I know that I need an object of class B, to change a variable member of B, but objects of B are not reachable in A. Is it possible by a pointer??
but objects of B are not reachable in A
If objects of class B are not reachable by class A there's no way you can modify them. Once you refactored your design, you should pass it as an argument to the function:
class A {
//several other things
void flagchange(B& obj) {
if (human)
obj.flag = 1;
}
};
I want to be able to toggle the flag from a method of class A for every object of B
You should declare your flag public variable as static in B:
class B {
public:
static int flag;
};
int B::flag = 0;
And then, from inside A:
class A {
//several other things
void flagchange() {
if (human)
B::flag = 1;
}
};
Related
We have classes A, B and C, all of which need access to a static variable staticVariable in class D.
Moreover, class A needs to have an instance of classes B and C like this:
class A{
public:
B instanceB;
C instanceC;
};
Class D hold the static variable of object type T:
class D{
public:
D() {
staticVariable.init();
};
static T staticVariable;
};
In the example classes B and C can be empty placeholder classes:
class B{
};
class C{
};
The main function creates an instance of A:
int main(){
A a;
/*...*/
}
Again, classes A, B and C need access to staticVariable. I've tried multiple approaches including inheritance and friend functions, however I always get dependency issues or linker errors I don't quite understand:
Error LNK2001 unresolved external symbol "public: static class T
D::staticVariable" (?window#D##2VT#sf##A) SortingAlgorithms
C:\Users\Dusan\source\repos\SortingAlgorithms\SortingAlgorithms\B.obj
is being reported in .obj files of classes A, B and C.
I'm not sure if I need an instance of D in main.
How do I implement this error-free?
And how do you do it for static objects that call a function for initialization?
I meant if the function is of the same class as the object you're trying to initialize, and is non-static, I can't seem to be able to call staticVariable.init();
I'm not sure if I need an instance of D in main.
You don't. static variables are global, they are shared by all the instances of the same class and you don't need to instantiate a class to be able to use such variables so they must be initialized regardless of class instantiation. That being the case they need to be initialized outside the class.
How do I implement this error-free?
Something like:
class B{};
class C{};
class A{
public:
B instanceB;
C instanceC;
};
class D{
public:
D(){};
static int staticVariable;
};
int D::staticVariable = 10; //<-- here, outside the class
int main()
{
//no instance of D needed
std::cout << D::staticVariable; // prints 10
D::staticVariable++;
std::cout << D::staticVariable; // prints 11
}
And how do you do it for static objects that call a function for initialization?
I meant if the function is of the same class as the object you're trying to initialize, and is non-static, I can't seem to be able to call staticVariable.init();
It's the same principle, you declare the object static within the class and initialize it outside:
class A{
public:
void init(){std::cout << "Do Something";} //non-static method
};
class D{
public:
static A obj; //declare
};
A D::obj{}; //<-- initialize outside the class
int main()
{
D::obj.init(); // prints 'Do Something'
}
// in D.hpp
class D {
public:
D() { ... }; // staticVariable is static, so the ctor has no business initializing it
void init();
static int staticVariable;
static D staticD;
};
// in D.cpp
#include "D.hpp"
int D::staticVariable = 10;
// Immediatly invoked initializing lambda expression
D D::staticD = []{ D tmp; tmp.init(); return tmp; }();
I was wondering how I would go about using a variable of a specific instance of a class within a function of another class.
To provide an example of what I'm trying to do, say I've 3 classes a,b and c. Class c inherits from class b, and a single instance of b and c are called within a method in class a and b respectively. How would I go about using the variable of int pos (see below) within a specific instance of class a in class c?
class a
{
private:
void B(); //Calls an instance of class c
int pos; //Variable that I want to use in c
};
class b : public c
{
private:
void C(); //Calls an instance of class b
};
class c
{
private:
void calculate(int _pos); //Method which requires the value of pos from class a
};
Help would be greatly appreciated, thank you!
Your code sample doesn't make much sense for me, and you aren't really clear what you want to achieve.
"How would I go about using the variable of int pos (see below) within a specific instance of class a in class c?"
Fact is you can't access any private class member variables from other classes.
Since class c and class b aren't declared as friend for class a, these cannot access the pos member from a::pos directly. You have to pass them a reference to class a; at some point, and provide public (read access) to pos with a getter function :
class a {
int pos; //Variable that I want to use in c
public:
int getPos() const { return pos; } // <<< let other classes read this
// property
};
And use it from an instance of class c() like e.g. (constructor):
c::c(const a& a_) { // <<< pass a reference to a
calculate(a_.getPos());
}
I'm not sure if I understand your problem, but if you want to access a member of a class instance from a non-friend non-base class, that member must be exposed of there must be some function that access it. For example:
class a
{
public:
int getPos() const { return pos; }
private:
void B(); //Calls an instance of class c
int pos; //Variable that I want to use in c
};
So say I have 3 classes: Base, A, and B.
Base is a base class for both class A and class B.
Base has a variable val that A and B can access.
How would I get it to work where I can set the val variable through class A, and it is reflected in class B?
For example:
I know this code below won't work because I am creating an OBJECT of the type a and b.
What I want to do is to simply have a and b share the same variable so that whenever a does something to it, it is reflected in b.
a aa;
b bb;
aa.SetVal(50000);
cout << aa.GetVal() << endl;
cout << bb.GetVal() << endl;
In the end I'd want both cout lines to print out 50000.
EDIT: The classes A and B will be doing different operations and just need to be able to access/change the val variable in base
You could make the member a static member of the base class, then all derived classes could access it, however any object of a derived that changes the static member would change it for every other object.
class Base
{
public:
int GetVal()
{
return val;
}
void SetVal( int newVal )
{
val = newVal;
}
private:
static int val;
};
// Need to instantiate the static variable somewhere
int Base::val = 0;
class A : public Base
{};
class B : public Base
{};
class Base {
static int value;
public:
virtual ~Base() { }
void setVal(const int& val) {
value = val;
}
int getVal() const {
return value;
}
};
int Base::value = 0;
class A : public Base {
};
class B : public Base {
};
#include <iostream>
int main() {
A a;
B b;
a.setVal(20);
std::cout << b.getVal(); // 20
}
That's a job for references, not for classes. Just have one class X and create a reference to the object:
X aa;
X& bb = aa;
aa.SetVal(50000);
std::cout << aa.GetVal() << std::endl;
std::cout << bb.GetVal() << std::endl;
The output will be:
50000
50000
Remember to always use the right tool for the job and keep things simple.
The main goal is that those two classes will be doing different things but will need to be able to access and share a single variable.
An idea to solve this is to extract the common variable in another class, namely S, which will be passed to A and B like this:
std::shared_ptr<S> s = new S();
A aa(s);
B bb(s)
Now, both aa and bb share the same S object and can modify it very easily. Notice that the constructor of both A and B should store the std::shared_ptr<S> as well:
class A { // and B
private:
std::shared_ptr<S> s;
public:
A(std::shared_ptr<S> as) : s(as) {}
};
The variable s will last as long as any of aa and bb is alive: when both aa and bb gets deallocated or go out of scope, the variable s will be deallocated as well.
If the type of the common variable should be on the stack, you can also just use references, but watch out for the lifetime of aa, bb and that variable:
int s = 0;
A aa(s);
B bb(s);
with:
class A { // and B
private:
int& s; // or any other type
public:
A(int& as) : s(as) {}
};
But as a general rule of thumb I'd avoid shared state between objects. Most of the time, depending on the context, you can refactor your code and get rid of the shared dependency.
If the shared value is static in the base class, then all instances of derived classes will see exactly that one base class member.
If the value is not static, then each instance of a class will have its own copy whether or not the value is in a base class.
Not sure I understand what you are trying to do. Do you want all instances of A and B to share the same value? if so, declare it as static in the base class.
if not, how do you want to choose which one will share the value?
Program:
class A
{
int a;
public:
void geta()
{
a=10;
}
void puta()
{
cout<<"a : "<<a;
}
};
class B : public A
{
int b;
public:
void getb()
{
geta(); b=20;
}
void putb()
{
puta(); cout<<"b : "<<b;
}
};
int main()
{
B ABC;
ABC.getb();
ABC.putb();
return 0;
}
The Problem:
The above program allocates memory for derived class object & calls its relevant methods.
The base class is inherited as public, and as the variable 'a' is a private member, it will not get inherited.
So, the program should not allocate memory for this variable.
But, when the above is executed, 'a' variable will be allocated even though it is not inherited.
Could anyone help me understand this?
Thank You.
as the variable 'a' is a private member, it will not get inherited. So, the program should not allocate memory for this variable.
Your assumption is mistaken. Public inheritance models an "is-a" relationship. That is, class Derived is-a Base. Anything you can do with a Base, you should be able to do with a Derived. In order for this to be true, it necessarily must contain everything that Base contains.
In your example, it's perfectly legal to say:
B b;
b.put_a();
that is, to use A methods on B object. This would not work if the a member was absent.
The base class is inherited as public, and as the variable 'a' is a private member, it will not get inherited.
When a base class member is declared as private it doesn't mean it does not get inherited. It just means that the member variable will be inherited (will be part of the derived class) but won't be accessible.
For example, in:
class A {
private:
int a;
int b;
// ...
};
class B : public A {};
auto main() -> int {
B b;
}
When we allocate B b; we are allocating both a and b member objects of the class A.
The variable a is inherited, though you have no access to it. For example, the following code would work:
class A {
private:
int x;
public:
int getXfromA() { return x; }
};
class B : public A {
public:
int getXfromB() { return getXfromA(); }
};
However, x cannot be directly accessed from B class here.
You're confusing storage with access control.
If object B inherits from object A, it has all of object A's methods and members, even if it cannot access them directly.
The purpose of private and protected is access control. If you mark members and methods as private, then nothing outside can access those methods and members. But, those things are part of the object nonetheless.
This allows you to implement class invariants without exposing the details, including classes that inherit from the base.
Here's an example that encapsulates capturing the creation time of an object in the base class:
#include <time.h>
#include <iostream>
class Base
{
private:
time_t create_time;
public:
Base()
{
create_time = time(0);
}
time_t get_create_time() { return create_time; }
};
class Derived : public Base
{
public:
Derived() { }
};
int main()
{
Derived D;
std::cout << D.get_create_time() << std::endl;
}
Derived doesn't know or need to know how the creation time was captured. It's a class invariant it inherited by deriving from Base.
This is a pretty simple example, but you could imagine more complex examples.
I have the following situation:
class B
{
public:
void methodInB();
};
class C
{
public:
void methodInC();
};
class A
{
public:
void methodInA();
private:
B objB;
C objC;
};
void A::methodInA()
{
objB.methodInB();
}
int main()
{
A objA;
objA.methodInA();
return 0;
}
I want to be able to call C::methodInC() from within B::methodInB(), but I'm not sure what the way to go about it would be (not without messing with globals).
My first idea was to add a C* pC pointer as a member of B, and then from methodInB() call it as pC->methodInC. This would require I set the pointer from within A before using the method (possibly in A's constructor). My problem is I may need to call other objects from within B if I add a D and E objects, and I don't want to fill the class definition with pointers.
Is there some other way of doing this? An implicit reference to the object the object belongs to? Kind of like this but for the parent? So I could at least do parent->objC->methodInC()?
I think the cleanest way would be to "inject the dependency", that is, to pass objC to methodInB, which would then invoke methodInC on that object:
void A::methodInA()
{
objB.methodInB(objC);
}
// ...
void B::methodInB(C &objC)
{
objC.methodInC();
}
Let every class B, C, D, E, etc. have a pointer to the A object of which they are subobjects.
class A;
class C;
class B
{
A* pA;
void MethodB();
};
...
void B::MethodB
{
(pa->CObject).MethodC();
}