-1

To simplify my problem, I have something like this:

class Base {

private:

protected:
    int a,b;
    string c;

public:
    [some functions here]

}

class Derived : public Base{

    [some variables and functions]

friend void function();

}

void function(){

int d[a][b];
[stuff]

}

basically, my void function needs to access stuff that is in the protected class of the base class. I'd like to keep those variables defined in the protected section. Is there anyway for function, which HAS to be friended into the Derived class, to be able to access a and b?

ecatmur
  • 152,476
  • 27
  • 293
  • 366
user1799323
  • 649
  • 8
  • 25

2 Answers2

0

You can define private methods in Derived: any method in Derived can access the protected members of Base.

Function is a friend of Derived, so it can invoke those private methods in Derived, which in turn access the protected members of Base.


Edit to reply to the comment below

The get_a() member method and the a member data are members of their classes. Instances of those members exist within instances of their classes. They don't exist except within an instance, so to access them you need to access them via an instance of the class.

For example, something like this:

class Derived : public Base{

    [some variables and functions]

    friend void function(Derived& derived);
};

void function(Derived& derived)
{
     int a = derived.get_a();
     int b = derived.get_b();
     // I don't know but even the following might work
     int c = derived.a; // able to access field of friend's base class.
}

void test()
{
    Derived* derived = new Derived();
    function(*derived);
    delete derived;
}
ChrisW
  • 54,973
  • 13
  • 116
  • 224
  • hmm, are you saying that the "friend void function();" line should go under "Private:" of the Derived class? – user1799323 Nov 05 '12 at 09:57
  • Hmm, so I wrote two functions in the private part of Derived class: 'class Derived : public Base{ private: int get_a(){ return a; } int get_b(){ return b; ] public: friend void function(); } void function(){ int a = get_a(); int b = get_b(); }' But this still tells me that get_a and get_b are out of the scope. ANy ideas what's wrong? – user1799323 Nov 05 '12 at 10:24
0

Your functions need to access a and b through an Instance of the class Derived as follows

void function()
{
Derived objectDerived;
int d[objectDerived.a][objectDerived.b];
[stuff]
}