Alessandro
Alessandro

Reputation: 876

Change object of all classes from a third class

I am having some trouble doing the following, I have 2 objects (instances of Class1.h and Class2.h) with a third object as a variable (instance of Obj.h), when I change the third object in one of the first objects from other class (Starter.h), I would like that that change would appear int the other object. I am using pointers to do it. for example:

Main.cpp

Class1* c1 = new Class1;
Class2* c2 = new Class2;

int main(int argc, char **argv)
{
    printf("Teste!");
    Obj* obj = new Obj();
    obj->setX(4);

    c1->setObj(obj);
    c2->setObj(obj);

    Starter s;

    printf("C

Upvotes: 2

Views: 85

Answers (1)

markus
markus

Reputation: 1651

Right now you are calling the default constructor of your class Starter in your main method:

Starter s;

So in this instance of Starter obj will be uninitialised. Change this to call the right constructor:

Starter s(c1);

Your Starter class is however lacking an accessor method for its Class1 instance variable at the moment. So even if you would call the right constructor you couldn't access the obj instance inside your Class1 intance c1. Try adding a Class1* getClass1() to your Starter class and you should be ready to go.


There are a couple of other issues with your example however:
- Your default constructor for Starter is leaving its instance variable uninitialised. This will yield undefined behaviour.
- Try to get accustomed to C++ initializer list syntax (see http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/)
- Try to fix your variable names

Upvotes: 2

Related Questions