OOP Question

I've been thinking lately with the method I'm using as many people suggest in making a class.

Some part of my code look like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
class test_t{
  test_t( double _x ){
    x = _x;
  }
  
  double get_x(){
    return x;
  }

private:
  double x; 
};


but after I tested...
Direct access to a variable is far more faster ( around twice as fast ) and I think it's breaking the OOP rules ( capsulation )

something like this

1
2
3
struct test_t{
  double x;
}


changing the function from the first example to this though
1
2
3
double& get_x(){
  return x;
}


have the same perfomence as direct access

there something I think might be a break trough for this, it's using "const" but I don't really know how to design a class that can be consted...

Hmmm, I think that the second one is what most people suggested because it does capsulation as what OOP code should be.
but if it's twice as slow or more that is quite bother some

Thank in advance and tell me if I'm misunderstood any part and please tell me your opinion.
If you return the addres of the variable then other functions would have direct acces to that variable (trugh the addres), so in that case it would be better to make that variable public.

Anyway I think returning the addres insted of the value is twice faster because the addres is (probably) 4 bytes long and double is 8 bytes.
I see ...

8 byte and 4 byte huh ?
That's the problem...

what I return is double
what if I return a vector which might be 1 MB in size ....

Sorry maybe I shoulde change my question to
Is there anyway to make a variable read-only without using const ???
What are you trying to do with it?
Topic archived. No new replies allowed.