Accessing the private members of a structure .

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

typedef struct {
    private :
    char name[80] ;
    int age ;
}man;

int main()
{
    man raman ;
    cout << "Enter name ";
    cin >> raman.name ;
    cout << "Enter age ";
    cin >> raman.age ;
    cout << "Details of the person " << endl;
    cout << "Name " << raman.name << " Age " << raman.age << endl;
    return 0;
}

Of course , I cannot access them directly . Is there any other way to access the private members of a structure ?
Nope. The point of making them private is to prevent direct access.
thanks for replying.
closed account (o1vk4iN6)
You can make functions and classes "friends" of man. This will let them access the private members.

1
2
3
4
5
6
7
8
9
10
11
12

class Matrix4 {
        friend Vec4        operator*( const Vec4 &, const Matrix4 & );

private:
        float              mat[ 4 * 4 ];
};

Vec4 operator*( const Vec4 & a, const Matrix4 & b ) {
        float m00 = b.mat[ 0 ]; // no access error
}


Of course I wouldn't see you making a function like "main" a friend, doesn't make sense.
Last edited on
Whenever I have something which contains only data , I put it inside a structure . However as said @xerzi , I could have used class also.

Should we use classes instead of structures in C++ ?

I read somewhere that they are relics of the past and just used for backward compatibility with C .




closed account (zb0S216C)
Raman wrote:
"Should we use classes instead of structures in C++ ? "

It doesn't make a difference, as both struct and class are equal, despite the default access level. And yes, struct is part of the backwards compatibility with C, but is allowed to behave like class.

What I tend to do is used struct for interfaces & PODs, and class for representing a physical object.

Wazzak
In C++ structure is a class with class key struct. :)
@OP:

Is there any other way to access the private members of a structure ?


Yes, through functions.
So we can do it like this :
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
32
33
34
35
36
37
38
39
40
41
#include<iostream>
using namespace std ;

struct Value1{
    private :
    int a;

    public :
    void setA(int b){
        a = b ;
    }

    int getA(){
        return a ;
    }
};

class Value2{
    private :
    int a ;
    public :
    int getA(){
        return a ;
    }

    void setA(int b){
        a = b ;
    }
};

int main(){
  Value1 value ;
  value.setA(34);
  cout << "The value using structure is " << value.getA() << endl;

  Value2 obj;
  obj.setA(20);
  cout << "The value using class is " << obj.getA() << endl;

  return 0 ;
}

Well , now they seem the same to me .
Last edited on
Topic archived. No new replies allowed.