0

I have 2 classes such as below:

class A : public C
{
void Init();
};

class B : public C
{
int a = 3;
};

How can i access the member of class B in class A?

class A::Init()
{
 class B. a  ???
}
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324

4 Answers4

2

Perhaps you want a static member, which you can access without an object of type B?

class B : public C
{
public:
    static const int a = 3;
};

Now you can access it from anywhere (including your A::Init function) as B::a.

If that's not what you want, then please clarify the question.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

You must create an instance of the class B and declare the variable public

class B : public C
{
    public:
    int a=3;//Data member initializer is not allowed in Visual Studio 2012, only the newest GCC
};

void A::Init()
{
 B b;
 b.a= 0;
}

If you don't want to create an instance of class B, declare the variable static

class B : public C
{
public:
    static int a = 3;
};

And then access it like this:

void A::Init()
{
   B::a=0;
}
Johnny Mnemonic
  • 3,822
  • 5
  • 21
  • 33
1

if you want access a "property" of class B as global, not a particular object then make variable static in this class

class B : public C
{
public:
    static const int a = 0;
};

and access it using B::a


alternatively:

class A{
public:
    void init(){
        static int a2 = 0;
        a1=a2;
    }
    int a(){return a1;}
private:
    static int a1;
};
int A::a1=0;
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • this looks great.. What if I have a function inside class B and I have a variable of a number, such as below : class B : public C { void Init(); }; class B::Init() { int a = 4; } How do I access this variable a in void A::Init() { ???? } – Alexander Andre Apr 04 '13 at 07:46
0

You can also try to add static function in your class. But I'm not sure if this what you are looking for.

class B: public C
{
public:
    static int GetA(void) {return a;}
private:
    static int a;
};
int B::a = 4;

class A: public C
{
public:
    void Init()
    {
    std::cout<<"Val of A "<<B::GetA()<<std::endl;
    }

private:
    int b;
};
praks411
  • 1,972
  • 16
  • 23