class a
{
private:
b *b_obj;
public:
void set(int);
};
a::a()
{
b_obj = new b;
}
a::set(int s)
{
b_obj->c = s;
}
class b
{
public:
int c;
};
is this code valid?
if no, how do i make b_obj of a particular object (say a_obj) of class a ,modifiable in another class c…if a_obj i created in another class d….i am scared of a_obj going out of scope in class c.
hope you understand my question.
thanks a lot for taking the time to read my post
The code is nearly valid.
class bneeds to be declared (or at least forward declared) before it is referred to inclass a, you do not specify the return type in the definition fora::set, and you have not provided a declaration fora‘a default constructor. Here is the revised code, along with a test harness:Now, just because the code is valid doesn’t mean it’s good:
cwhen default-constructingb.b‘s. Use automatic variables instead, whenever possible. Among the the reasons for this are …deletethebyounew‘ed ina‘a constructor. This results in a memory leak. If you had avoided the use of dynamic allocation in the first place, this would not be an issue.