Error accessing private data in a class

Nov 19, 2008 at 9:45pm
I'm new to programming and I'm having a problem with an assignment I was given to add complex numbers.
When I run the code it always points to these sections of code stating that a and b are private. I am guessng it is because am usng the complex type within the complex class.

Could somebody give me an idea as to where I'm going wrong.

Thanks



1
2
3
4
5
6
7
8
9
class complex
{
   float a, b;

   public:
      void input(float real, float img);
      void display(complex c);
      complex sum(complex, complex);
};


1
2
3
4
5
6
7
complex::complex sum(complex c1, complex c2)
   {
      complex c3;
      c3.a = c1.a + c2.a;
      c3.b = c1.b + c2.b;
      return (c3);
   }
Nov 19, 2008 at 10:14pm
1
2
3
4
5
6
7
complex::complex sum(complex c1, complex c2) //ERROR ON THIS LINE
   {
      complex c3;
      c3.a = c1.a + c2.a;
      c3.b = c1.b + c2.b;
      return (c3);
   }


You mean complex complex::sum(complex c1, complex c2)
Notice the position of the ::


By the way, a sum function written as a member function like this would be awkward to use.
Nov 19, 2008 at 10:25pm
The above poster is correct, if you want to add two objects together like this you should overload the addition operator. Try googling "c++ overload operator". After overloading the add operator you can do stuff like:

1
2
// c1 and c2 are complex
complex c3 = c1 + c2;


instead of:

 
complex c3 = c1.sum( c1, c2 );


At the very least, if you don't overload the addition operator, make the function static.
Nov 26, 2008 at 11:51pm
I agree, overloading the + operator is way better and easier to use afterward. A few months ago I made, for fun, a class named complex.h. It was getting right to the point of overloading operators. I just wanted to remember such things hehe, so anyway you wanna see it ? I know it is quite not good for your learnings... :D
Nov 27, 2008 at 1:07am
The actual problem you are experiencing is that .a and .b are private members. Therefore you cannot access the .a or .b of the parameters passed in.

You should make a function called.
1
2
float getA() { return a; }
float getB() { return b; }


then use
c3.a = c1.getA() + c2.getA();

Welcome to Encapsulation. 1 of the 3 Fundamentals of Object-Orientated Development
Nov 27, 2008 at 4:34pm
That should be ok, though. sum() is a member function of complex, and should therefore be able to access the private data members of its own instance or of any other instance of complex passed in.

Anyway, I tend to follow the rule of making non-public things protected rather than private unless there is a strong reason why derived classes should not have direct access to the members.



Last edited on Nov 27, 2008 at 4:36pm
Topic archived. No new replies allowed.