1
    #include <iostream>
    using namespace std;

    class B{
    public:
        int x;
        void setx(int a){
            x =a;
            cout<<"Inside set "<<x<<endl;
        }
        void show();
    };

    void B::show(){
        cout<<"inside show "<<x<<endl;
    }

    class A{
    public:
        void func();
        void func2();
        B bb;
    };
    void A::func(){
        bb.setx(100);
        bb.show();
    }
    void A::func2(){
        bb.show();
    }
    int main()
    {
       A a;
       B b;
       a.func(); 
       b.show(); 
       a.func2(); 
       return 0;
    }

Changes are applicable only to class A, where actual value in class B is not changing. I tried static but its showing error.

OUTPUT I'M GETTING : Inside set 100 inside show 100 inside show 0 inside show 100

OUTPUT I WANT : Inside set 100 inside show 100 inside show 100 inside show 100

Mr. Sai
  • 13
  • 3
  • 5
    Object `b` in `main` and object `bb` inside object `a` are two completely different objects. They are not related to each other. As such, changing `a.bb` does not do anything with `b` in `main`. The output you get is what you should expect. – Yksisarvinen Jun 18 '19 at 14:09
  • Note that `b.show()` has undefined behaviour due to the indeterminate value of `b.x`. Always initialise your variables. And get a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Jun 18 '19 at 14:14
  • @molbdnilo Is it indeterminate? I thought default constructor zero-initializes all members (*but I can't remember the initialization rules for my life, so I might be wrong*) – Yksisarvinen Jun 18 '19 at 14:20

2 Answers2

0

A class is not an object. It is a user defined data type which can be accessed and used by creating an instance of that class. An instance of the class is an object.

Now, in your main function, when you instantiate an object of class A by writing A a;, the constructor of class A instantiates the data member bb (which is of type B). You then create another object of type B in your main function, by writing B b;. This instantiation of class B has nothing to do with the data member bb in your class A. To get your desired output, you would need a.bb.show().

To be clear:

struct Airplane {};

Airplane a1, a2, a3;

I have 3 airplanes, which are each an instantiation of the class Airplane, 3 objects of type Airplane. Changing a1 doesn't imply changing a2 and a3.

mfnx
  • 2,894
  • 1
  • 12
  • 28
0

Try:

int main()
{
   A a;
   B b;
   a.func(); 
   a.bb.show(); 
   a.func2(); 
   return 0;
}

You're calling show() on wrong object. Since a has it's own bb, you need to use a.bb to see change. b in main is different object (even if of the same class).

Radosław Cybulski
  • 2,952
  • 10
  • 21