Alexander Andre
Alexander Andre

Reputation: 11

access member in different classes

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  ???
}

Upvotes: 0

Views: 93

Answers (4)

praks411
praks411

Reputation: 1992

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;
};

Upvotes: 0

4pie0
4pie0

Reputation: 29744

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;

Upvotes: 1

Johnny Mnemonic
Johnny Mnemonic

Reputation: 3922

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;
}

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254711

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.

Upvotes: 2

Related Questions