I have a program that has a single instance of the class class A and many instances of the class class B, where every instance of class B has a pointer to a single instance of class A. I thought I could initiate them in main() and then pass the address of the single instance of class A to all instances of class B. I want to know if this is correct, I have been looking at inheritance but from my understanding (which is often wrong) if you inherit another class then that class gets initiated every time so creates a many to many relationship whereas, I want a one to many. I have attached some code. Any suggestions would be greatly appreciated.
// C/C++ standard library
#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;
class A {
public:
double get_value(void) {
return value;
}
private:
double value;
};
// Forward declare A if split over files
class B {
public:
void assign_pointer(A class_a_to_assign) {
class_a = &class_a_to_assign; // assign the pointer the address to point to
}
void update_my_value(void) {
value_b += class_a->get_value();
}
double get_value(void) {
return value_b;
}
private:
double value_b = 0.1;
A* class_a; // pointer to class A
};
int main() {
cout << "hello world" << endl;
// create 2 instances of B there could be thousands of these tho.
B b1;
B b2;
// create 1 instance of A
A a1;
// Now I want both instances of the B class to point to the one instance of A
b1.assign_pointer(a1);
b2.assign_pointer(a1);
// THen do stuff with B so that if any changes occur in A, then they can be automatically updated in class B through the pointer
b1.update_my_value();
b2.update_my_value();
cout << b1.get_value() << " and " << b2.get_value() << endl;
return 0;
}
a1before all theBobjects, to ensure it outlives them, since they depend on it.Awouldn't suffice forB's definition, and your example reads from the uninitializedA::value.) There's nothing else (obviously) wrong here (even if significant improvements could be made)--is that your whole question?Bcan only be instantiated from anA*by doing it in the constructor:explicit B(A* a) : class_a(a) {}.