1

I am super-new to classes and still wrapping my brain around how they work. Any help/advice/pointers-> are appreciated!

I have two classes. Within the second class is an array of the first class. I am trying to assign values to the private member variables contained in the array of the first class.

I get this error message when compiling:

hw2Test.cpp: In member function 'void bar::set(int)':
hw2Test.cpp:11:7: error: 'int foo::x' is private
   int x;
       ^
hw2Test.cpp:34:12: error: within this context
  foodoo[0].x = x;
            ^

Here is the code:

#include <iostream>
using namespace std;


class foo
{
    public:


    private:
        int x;
};

class bar
{
    public:
        void set(int x);

    private:
        foo foodoo[1];
};

int main()
{
    bar tar;

    tar.set(1);

    return 0;
}

void bar::set(int x)
{
    foodoo[0].x = x;
}

1 Answer 1

1

foo::x is declared as private, so only methods of foo can access it. But you are trying to access x inside of a method of bar instead, which does not have access to foo's private members.

To give bar access, you need to either:

  1. declare foo::x as public:

    class foo
    {
        public:
            int x;
    };
    
    void bar::set(int x)
    {
        foodoo[0].x = x;
    }
    
  2. declare a public setter:

    class foo
    {
        public:
            void set(int i);
    
        private:
            int x;
    };
    
    void foo::set(int i)
    {
        foodoo[0].x = i;
    }
    
    void bar::set(int x)
    {
        foodoo[0].set(x);
    }
    
  3. declare bar as a friend of foo:

    class foo
    {
        public:
    
        private:
            int x;
    
        friend class bar;
    };
    
    void bar::set(int x)
    {
        foodoo[0].x = x;
    }
    
Sign up to request clarification or add additional context in comments.

3 Comments

There is a third option, provide accessor methods.
By provide accessor methods, do you mean calling a fx inside of bar that calls a fx inside of foo so I can get to foo's naughty bits?
@BuckWheat yes, exactly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.