1

I am new to C++.While working with class and object I tried this code:

#include <bits/stdc++.h>
using namespace std;
class patient {

string name;
int age;
int room;
};
int main()
{
patient me;
me.name = "Zuahir";
me.age = 16;
me.room = 365;
cout << me.name;

return 0;
}

But this gives me a member inaccessible error. Kindly help me in this case

  • 1
    It looks like you would beneift from one of [these](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Learning by guessing is very inefficient, and C++ is almost entirely dissimilar to Python. – molbdnilo Apr 21 '20 at 11:50
  • I am good at python, just learning c++ for competetive programming. – Zuhair Abid Apr 21 '20 at 11:54

2 Answers2

4

class-members are private by default in c++. If you want to acces them directly, make them public:

class patient {
  public:
    string name;
    int age = 0;//<-- don't leave those int's uninitialized ;)
    int room = 0;
};

Or declare it as a struct:

struct patient {
    string name;
    int age = 0;
    int room = 0;
};
melk
  • 530
  • 3
  • 9
  • your wording suggests that a struct is not a class, but a class declared with the keyword `struct` is also a class. Really the only difference is default access – 463035818_is_not_an_ai Apr 21 '20 at 11:55
  • @idclev463035818 Right you are, changed my wording accordingly – melk Apr 21 '20 at 11:58
  • `std::string` is not POD, and any `struct` or `class` that contains a non-POD type is also non-POD. In any event, a `struct` and a `class` are identical in C++, except for default access and inheritance being `public` rather than `private`. It is equally correct to describe a `struct` as a `class` with different default access, as it is to describe a `class` as a `struct` with different default access. – Peter Apr 21 '20 at 12:31
  • @Eljay, Peter Yes, my bad, removed the whole POD part. – melk Apr 21 '20 at 12:33
2

In c++ default access modifier for a class is private.

Please use public access modifier before class attributes.

Like:

class patient {
  public:
   string name;
   int age;
   int room;
};
Bathsheba
  • 231,907
  • 34
  • 361
  • 483