I hate when I have to acces a class data member like myclass.get_x();
I would like to simply write myclass.x;
But I also want to stay with private x,
I just want to read like myclass.x, but dont want overwrite it.
It is somehow possible?

Within the same class -- yes. Otherise, no.

I want something outside not inside!

noway to do it , then why it's private if you can access it outside the class

I think he/she wants to use the syntax as if it is public. @merse, no, I don't believe you can do that...

If you want to access the data member from another class or function specifically, you can use the "friend" keyword, as such:

#include <iostream>

class Bar; //forward declaration

class Foo {
  public:
    void someMethod(const Bar& a);
};

class Bar {
  private:
    int x;
  public:
    Bar(int aX) : x(aX) { };

    friend class Foo; //declare Foo as friend, granting access to private members
};

void Foo::someMethod(const Bar& a) {
  std::cout << a.x << std::endl;
};

int main() {
  Foo f;
  Bar b(10);
  f.someMethod(b);
  return 0;
};

But generally, friend relationships are an indication of bad software design, i.e., poor separation of the purpose of the different classes/objects.

You can also avoid the ugly accessor functions (get and set) with simple constness:

class Bar {
  private:
    int x;
  public:
    Bar(int aX) : x(aX) { };

    int X() const { return x; }; //provide read-only access to x.
    int& X() { return x; }; //provide read-write access to x.
};

But, in the above case, you would just be better off making x a public member (there is nothing wrong with doing that if it makes sense for your application to expose x).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.