private objects

Hello!, im trying to create a matrix of chars, but i get an error of "char object::mat [40][40]’ is private".


i've 2 files one is "a.h" and the other "b.cpp"

The 1st one is "b.cpp"

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "a.h"
using namespace std;

int main()
{
	object matrix;

        matrix.create(matrix.mat);


return 0;
}


The 2nd one is "a.h"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class object
{
	public:
	   void create(char (mat)[40][40]);
	private:
	   char mat[40][40];  
};


void object::create(char (mat)[40][40])
{
	for (int i=0;i<=39;i++)
	{
	   for (int j=0;j<=39;j++)
	   {
	      mat[i][j]=' ';
	   }
	}
}


How i fix this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class object{ //consider a better name for your class
public:
   object();
private:
   char mat[40][40];
};

object::obect(){
   for(int K=0; K<40; ++K)
      for(int L=0; L<40; ++L)
         mat[K][L] = ' ';
}

int main(){
   object matrix;
}
Don't pass mat as a parameter to create().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
class object
{
	public:
	   void create();

	private:
	   char mat[40][40];
};


void object::create()
{
	for (int i=0;i<=39;i++)
	{
	   for (int j=0;j<=39;j++)
	   {
	      mat[i][j]='';
	   }
	}
}


int main()
{
    object matrix;

    matrix.create();

    return 0;
}
Line 9 in b.cpp references matrix.mat. mat is a private member of matrix, so it can only be referenced from with a member of the class.

In fact there is no need to pass mat to object::create, since object::create implicity has access to it.

Change your files as follows:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include "a.h"
using namespace std;

int main()
{  object matrix;

    matrix.create();
    return 0;
}


1
2
3
4
5
6
7
class object
{
    public:
        void create ();
    private:
        char mat[40][40];  
};


1
2
3
4
5
6
7
void object::create ()
{  for (int i=0;i<=39;i++)
    {   for (int j=0;j<=39;j++)
         {   mat[i][j]=' ';
         }
    }
}


BTW, what you're doing in create should really be done in object's default constructor rather than a separate function.
Thank you guys, i did it like AbstractionAnon said, but now i get this error u_u' :

/tmp/cccLju3V.o: In function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0xa5): undefined reference to `std::ios_base::Init::Init()'
main.cpp:(.text+0xb4): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
Last edited on
That look like some kind of linker error indicating that the linker couldn't find some ios_base stuff. Make sure you have the right headers included in your file and that the linker knows where to look for standard library files.
Thankyou, i fixed didnt realise that i was compiling with gcc instead of g++ ... lol .

Now its working fine, thank you :D
Topic archived. No new replies allowed.