hello February 2016

Set a value of a class from another class

I'm trying to set the value of a member of a class from another class using this snippet. Here is a sample of the code I'm trying to make work

class A
{
private:
int a;
public:
A()
{
    a = 0;
}
A(int val)
{
    a = val;
}
int GetA()
{
    return  a;
}

void SetA()
{
    a = 290;
}
};


class B
{

B(){};

 void SetB()
{
     A a;
     a.SetA();
}

};


int main(){
A a;
B b;
b.SetB();
cout << b.GetA();

}

How can I make this code pint out 290.I currently prints out 0

Answers


Michael Albers February 2016

In SetB your A variable is a temporary that is destroyed when the function returns.


mindriot February 2016

The way it is written in your snippet, your code won't compile, because B has no method GetA(). From your use case (the code in main()), I suspect you either want B to inherit from A:

class B : public A
{
public:
  B() {];
  void SetB()
  {
    SetA();
  }
};

although that doesn't make too much sense, because in this case you could just call b.SetA() directly. Or, you want an object of type A as a member of B:

class B
{
public:
  void SetB()
  {
    a.SetA();
  }
  int GetA()
  {
    return a.GetA();
  }
private:
  A a;
};

But it's a bit hard to tell from your snippet what you're actually trying to achieve.

Also, you probably want your Get…() methods to be const.


makar February 2016

If you;re trying to achieve what I think you're trying to achieve then you're nearly there, it is just that you are creating two versions of A, one on the main stack, and one that is a temporary inside B::SetA()

try passing A as a reference parameter to B, so that there is only one version of A.

void SetB(A& a)
{
     a.SetA();
} 

then your calling code would be:

A a;
B b;
b.SetB(a);
cout << a.GetA();

Alternatively, pass a in the constructor of B and store A as a reference member in B;

Post Status

Asked in February 2016
Viewed 2,529 times
Voted 6
Answered 3 times

Search




Leave an answer