-3

Hi I'm very new to c++. I just write a c++ code which is following :

#include<iostream>
using namespace std;
class complex
{
 float x,y;
};
int main ()
{
  complex a; 
  a.x=500;
   a.y=600;
cout<<" the value of a.x = "<<a.x<<"\n" ;
cout<<" the value of a.y = "<<a.y<<"\n" ;

return 0;
}

when i compile the program it give me following error:

try.cpp: In function ‘int main()’:
try.cpp:5: error: ‘float complex::x’ is private
try.cpp:10: error: within this context
try.cpp:5: error: ‘float complex::y’ is private
try.cpp:11: error: within this context
try.cpp:5: error: ‘float complex::x’ is private
try.cpp:12: error: within this context
try.cpp:5: error: ‘float complex::y’ is private
try.cpp:13: error: within this context 

i resolve the error by just declaring data member public ;

Now what should i do to make this thing work with private member? Why can't i access the private member with the object of class? How can i directly access the private data members or why i cant use the data member of class directly with class object ? What's the reason behind it?

How class is implemented in memory? How class prevent us or stop us to use its private data or implements it's security mechanism ? what is compiler do when is saw a class? How compiler implement the class and its security mechanism ?

Please explain this to me

Para
  • 2,022
  • 5
  • 34
  • 73
user513164
  • 1,788
  • 3
  • 20
  • 26

6 Answers6

3

Now what should i do to make this thing work with private member?

If you make them private, then you can write constructor and add other useful functions to your class, to do operations on your complex objects:

class complex
{
   float _x;
   float _y;
   public:
      complex(float x=0.0, float y=0.0) : _x(x), _y(y) {}
                                       //^^^^^^^^^^^^^its initialization list!

      complex operator + (const complex & c)
      {
          return complex(_x + c._x, _y + c._y);
      }
      ostream & print(ostream & out) const
      {
          return out << "(" << _x << ", "<< _y << ")";
      }
      void print() const
      {
          print(cout);
          cout << endl;
      }

      //and so on
};

ostream & operator << (ostream & out, const complex &c)
{
    return c.print(out);
}

Test it:

int main ()
{
  complex a(500,600);
  complex b(80,60);
  complex c = a + b; //operator+() gets invoked!

  a.print();
  b.print();
  c.print();

  cout << "\nprint using cout!" << endl;
  cout << a << endl;
  cout << b << endl;
  cout << c << endl;
  return 0;
}

Output:

(500,600)
(80,60)
(580,660)

print using cout!
(500,600)
(80,60)
(580,660)

See the Online Demo : http://www.ideone.com/TiGat

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Just saying, you forgot to add a "=" sign in your y assignment. – Andy Ibanez May 18 '11 at 05:00
  • OK I did not understand concept of your constructor . what type of constructor is this . i didn't find any such type of constructor. will you explain me working of this type constructor. I didn't get the concept of operator +. what is it? And How the code is working? please explain . what about my rest of question . – user513164 May 18 '11 at 05:14
  • 3
    @user513164: That is called initialization list. And for other questions. Get a book on C++. You need to read some good book first. – Nawaz May 18 '11 at 05:17
0

Your a.x and a.y are trying to access the x and y members from outside the class. If they aren't public, those attempts will fail as you have seen.

If you want the default access to be public instead of private, use struct instead of class.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 1
    thanx for help, but i know that , but what about rest of the question i asked . Please read my question care fully – user513164 May 18 '11 at 05:17
  • 1
    @user513164, if you don't know the difference between public and private there's not much I can do to help you. This is very basic stuff. – Mark Ransom May 18 '11 at 05:26
  • pal iknow all about this access specifier stuff but all i want to know what is going inside the memory . how thing are implemented inside the memory . what compiler do when its saw a class name ? how it woks or implement the different phenomena of oops – user513164 May 18 '11 at 05:44
0

By default fields you define inside a class are "private" and can only be used by the methods of that class.

You need to define x and y as "public" members of the class.

class complex
{
 public:
 float x,y;
};
James Anderson
  • 27,109
  • 7
  • 50
  • 78
0

public,private and protected are compile time concepts. During runtime, they're not even existent. That cleared up, lets move on to why you can't access private data.

private is just what it says - PRIVATE. And that is total, no access from anywhere but the class itself. A class, by default, is private until specified otherwise.
If you want public by default, take a struct. Other than the default "privacy", they're exactly the same.

struct complex{
  float x;
  float y;
};

Now you can access the members from anywhere.


For further stuff, and from my impression of your questions, it seems you really really need a good C++ book.

Community
  • 1
  • 1
Xeo
  • 129,499
  • 52
  • 291
  • 397
  • Pal i know this concept ,all i want to know what happened inside the memory or how this security mechanism is implemented. what is running inside machine.like we know when we declare an array a pointer is formed inside the memory and rest of array entry use this base address and subscript as offset .similarly i want to know how class is implemented what happened in memory. what compiler do on a class name or how compiler implements a class? – user513164 May 18 '11 at 05:25
  • @user: Well, that's the very first sentence. Security doesn't exist beyond compilation. If you look at assembly, it doesn't even know about types other than pointer! Basically, the compiler only checks if you're allowed to do that. That's why you can actually access such stuff through hacky casts, same as with `const`, which is also only a compile-time concept. – Xeo May 18 '11 at 05:29
  • need more detail and explanation about imlementation of class – user513164 May 18 '11 at 05:40
  • @user: You need a good book. Also, search around on SO. There are more than enough answers on that topic here. – Xeo May 18 '11 at 05:45
0

Data protection and abstraction are the fundamental concepts of Object Oriented programming. In addition to Mark's Answer, I'd suggest you to read any of your favorite C++ programming books like Eric Nagler's C++, A Hands On Approach or C++ Primer etc.

sarat
  • 10,512
  • 7
  • 43
  • 74
0

To access a class's private member, you can:

  1. Providing public methods to read and write the value of private members. In this way, the class can take full control of the access operations.
  2. Providing public methods to return pointers or references of private members. This is not a good way, as the state of object may be destroyed.
  3. Declear classes or functions as friend of the class that contains the private member, so that the friends can access all member. Be sure the friends operate correctly on the class's data member.

The private, protected and public take effect only at compile time, preventing mistaken codes to destory the state of a object. They have no business for runtime security controling.

Let's take an example, see the simple stack class below:

class statck
{
private:
    static const int buffersize = 100;
    int buffer[buffersize];
    int count;
public:
    stack();
    bool Push(int value);
    bool Pop(int value);
    int GetCount();
}

The count memeber logically represent how many value have been pushed into the stack, it's value is managed by Push, Pop and constructor, and should not be changed by code using stack class object, like:

statck s;
s.count = 10;

The code upside is logically meaningless. If the count is public, the code could be compiled, and the mistake was harder to revealed, and by declearing count as private, the mistake is obvious and causes a compiling error.

All the thing access modifiers(public, protected and private) done is to tell compiler, whitch member of a class could appear in some expressions in code other than the class's member method. I didn't use the phrase "access", I think that's what confused you.

The access modifiers won't affect the memory layout produced by compiler to represent the object. Stricly, the layout is depending on compiler and platform's word size, but generally on a 32bit system, the statck object will be a 404 byte long memory block, 400 byte for buffer and 4 byte for count, no matter the buffer and count is public or private. And when the program is running, every code that get the address of the 404 byte memory block can read and write them, the private has nothing to do with this.

  • pal i like your answer most will u please explain me what is object state n how it is created or implimented – user513164 May 18 '11 at 06:31
  • OK, "object state" is not a formal term, I personally use the phrase to refer the logical correctness of one object's data member values and their relationship. See the example I added to the answer. – Liu Yongtai May 18 '11 at 08:02