-4

I have a class B with a pointer attribute of class A with a method that assigns the pointer attribute to the variable of the other class A. Yet this variable is private, assigning the variable therefore create an error. How can I solve this issue?

#include<iostream>

using namespace std;

class A {
private :
    int x;
public:
    A(int);
    ~A();
};

class B {
private :
    A * pA;
    int y;
public:
    B(int, int);
    ~B();
    void imprimer();
};

void B::imprimer() {
    cout << "B::imprimer: " << pA->x << " " << y << endl;
    }


main()
{
    B to(1, 2);
    to.imprimer(); //instruction (1)
}

Gives the following result :

    $ g++ td4Exercice1_2.cpp -o td4Exercice1_2
td4Exercice1_2.cpp: In member function ‘void B::imprimer()’:
td4Exercice1_2.cpp:7:6: error: ‘int A::x’ is private
  int x;
      ^
td4Exercice1_2.cpp:24:33: error: within this context
  cout << "B::imprimer: " << pA->x << " " << y << endl;
Revolucion for Monica
  • 2,848
  • 8
  • 39
  • 78
  • 1
    "How can I solve this issue?" It's not an issue to be solved, it's what's supposed to happen. –  Mar 19 '17 at 16:23
  • 2
    Everything works as intended. You are not supposed to touch private members of others, and C++ is not letting you to do so. Don't see any issue here. – n. m. could be an AI Mar 19 '17 at 16:24

1 Answers1

0

What you are missing are the class get() and set(int) methods for class A OR You have not declared Class B to be a friend of Class A.

A's x is a private variable within Class A. Only Class A can modify its variables, unless you do a few things.

You declare Class B to be a friend of Class A.

class B; // you must 'declare Class B before Class A for this to work

class A {
friend class B;
private :
    int x;
public:
    A(int);
    ~A();
};

This would allow class B full access to anything in Class A. BUT this is a POOR design.

There complex ways to do this as shown in "C++ Primer", S. Lippman that allow the "<<" operators to friend the class for output. QED.

The least intrusive way to do this is to create a new method in class A.

class A {
private :
    int x;
public:
    A(int);
    ~A();
    int getX( void) { return( x ) };
};

void B::imprimer() {
    cout << "B::imprimer: " << pA->getX() << " " << y << endl;
    }

now you can get the value of A::x without being able to change it.

This does lead to some greater design problems in that you now have the last value of A::x, though possible not the current value of A::x. x could have been modified before you begin to use the value you have for x.

Further study of using 'friend' with "<<" ">>" operators will show you a better way depending on what the big picture is for your program.

Vanderdecken
  • 195
  • 1
  • 9