I am new into classes, and I have been trying to create this simple class code but every time I get an error. It works fine when I don't use the access specifier private, but I want to practice how to use private. Could you please tell me what's wrong?
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string name;
int ID;
public:
void setName(string);
string getName();
void setID(int);
int getID();
};
void Student::setName(string n)
{
name=n;
}
string Student::getName()
{
cout<<name;
return name;
}
void Student::setID(int i)
{
ID=i;
}
int Student::getID()
{
cout<<ID;
return ID;
}
int main ()
{
Student S;
cout<<"Enter Student name: ";
cin>>S.name;
cout<<"Enter students ID: ";
cin>>S.ID;
cout<<"The student's name is "<< S.name<<endl;
cout<<"The student's ID is "<< S.ID<<endl;
return 0;
}
In your main function you are trying to access the name and IDmember of your class. Which are private... Since you are outside the scope of the class Student, the compiler shouts at you.
You should do this (as you've implemented setters and getters):
int ID(0);
std::string name;
std::cin >> name;
S.setName(name);
std::cin >> ID;
S.setID(ID);
You have to access your private fields using setters/getters to set or retrieve their values, you can't use them with the class dot notation because they're private and you can access to them only using public methods
What's wrong : You are accessing private members without using a class member function (outside of the class scope).
Private members are useful when you want to protect a value from uncontrolled access. Like when the modification of a value must undergo a certain verification (which would be implemented in class functions).
In your code, you made sure name and ID are private, which means both can only be accessed using class functions (like the constructor or the getter and setter).
If you wanted, you could create a class named classroom (which would contain many students, stored in a vector).
In that class, you could make sure than when a student is added, it's ID is automatically generated and does not equal any other ID. In that case, it would be important to put the student vector private since it would require some sort of validation.
class Student
{
private: // anything that wants to access members below
// this must be defined as a class member, or the equivalent
string name;
int ID;
public:
void setName(string); // can access private members
string getName(); // can access private members.... should be const
void setID(int); // can access private members
int getID(); // can access private members, should be const
};
Related
I want to keep track of the number of students in my system so, My idea was to make a static datamember in the "StudentController" class called "_numOfStudents" and increment it with the Student's constructor but it didn't work so, I moved it into the "Student" class and made that when a Student object is created the number increment by the help of the constructor. The problem is: isn't it not the Student class's business to know how many students are there thus breaking the principle of least privilege. what can I do better to keep track of the student objects' count.
Student(string firstName, string lastName, int age,vector<float>&subjects)//Student conctructor
{
SetFirstName(firstName);
setLastName(lastName);
SetAge(age);
SetMarks(subjects);
this->m_id++;
StudentController::_numberOfStudents++;
}
class StudentController//this is where i declared the static data member
{
private:
list<Student> _students;
public:
static int _numberOfStudents;
StudentController() {};
StudentController(list<Student>& st) :_students(st) {};
}
}
};
int StudentController::_numberOfStudents = 0;
When you try to do StudentController::_numberOfStudents++; in the constructor, the StudentController class is not yet defined, therefore the compiler doesn't know about that class and its static member.
Maybe keeping track of the students shouldn't be the role of the Student class itself. Instead it should be the role of a separate Classroom object:
struct Student;
struct Classroom {
void add(Student&) {
m_count++;
}
size_t count() const { return m_count; }
private:
size_t m_count{0};
};
struct Student {
Student(Classroom& classroom) {
classroom.add(*this);
}
};
int main()
{
Classroom classroom;
Student alice{classroom};
Student bob{classroom};
assert(classroom.count() == 2);
}
This question already has answers here:
Allowing access to private members
(4 answers)
Can I access private members from outside the class without using friends?
(27 answers)
Closed 1 year ago.
I want to change the data in the private members but the delete_Data() function is outside the class so how to get the members without being declared in the class and erase them using the delete_Data() functionthe only way it works for me it to declare delete_data()function in the class on public section but
our teachers said you should only use this method
i need help pls thank you
for eg
Enter your Name: John
Enter your id: 1234
Name: John
ID:1234
Name :
ID:0
#include <iostream>
#include <string.h>
using namespace std;
class data{
private:
string name;
int id;
public:
void add_Data()
{
cout<<"Enter you Name :";
cin>>name;
cout<<"Enter your id :";
cin>>id;
}
void display_Data(){
cout<<"Name :"<<name<<endl;
cout<<"ID :"<<id<<endl;
}
};
void delete_Data(){
name="";
id=0;
}
int main(){
data one;
one.add_Data();
one.display_Data();
delete_Data()
one.display_Data;
return 0;
}
Usually✝, the member functions and the friends of the class can access the private members of a class, via an instance of the class.
Therefore, in your case, make the delete_Data function as friend function.
class data
{
private:
std::string name;
int id;
public:
// ...
friend void delete_Data(data& obj);
};
void delete_Data(data& obj)
{
obj.name = "";
obj.id = 0;
}
Now in the main()
data one;
delete_Data(one);
Also note that, you need to pass an instance of the data class to access the members of the class.
Side notes:
✝There are other tricky ways, by which we can also
access the member. However, the whole point of the
public/protected/private modifiers, is not to do that.
See more:
Can I access private members from outside the class without using friends?
Also see
Why is "using namespace std;" considered bad practice?
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class person {
private: char name[50];
int age;
public: void get_name() {
cout<<"Enter name"<<endl;
gets(name);
}
void put_name() {
cout<<"Name : ";
puts(name);
cout<<endl;
}
void get_age() {
cout<<"Enter age"<<endl;
cin>>age;
}
void put_age() {
cout<<"Age : "<<age<<endl;
}
};
class student : public person {
private : int roll;
public : void get_roll() {
cout<<"Enter roll"<<endl;
cin>>roll;
}
void put_roll() {
cout<<"Roll : "<<roll<<endl;
}
};
int main() {
student A;
A.get_name();
A.get_roll();
A.get_age();
A.put_name();
A.put_age();
A.put_roll();
getch();
clrscr();
return 0;
}
There are following queries:
If private members of class person are not inherited in class student then how can an instance of class student store values in them?
Shouldn't the variables just not exist in the class student?
Note: I am using old compiler for a college project.
If a Student wants to access the Person fields, the simplest way is make them protected, so they can be accessed by all derived class of Person.
Another way is use public getter/setter methods (you can even set them protected, but at this point is better use protected fields), in this way all classes can see and set the fields of Person.
Indeed, even if a variable is declared private in the base class, it exist in the derived class ( a Student is in any case a Person, so the field in Person must be initialized) but it can't be reached by her.
A is an object of type Student and it can access protected or public member function and data member of class Person. Now answer to your query, you are trying to use the function of class Person using object of class Student which is possible (as inherited publicly) and since the function and those private data member are part of same class (Person), so those function can use the variable.
Note : private, public and protected member have no effect within same class.
Design a class named PersonData with the following member variables:
• lastName
• firstName
• address
• city
• state
• zip
• phone
Write the appropriate accessor and mutator functions for these member variables.
Next, design a class named CustomerData , which is derived from the PersonData class.
The CustomerData class should have the following member variables:
• customerNumber - The customerNumber variable will be used to hold a unique integer for each customer.
• mailingList - The mailingList variable should be a bool . It will be set to true if the customer wishes to be on a mailing list, or false if the customer does not wish to be on a mailing list.
The CustomerData class should also maintain a static variable to keep track of the total number of customers created and a static function to access that number.
Write appropriate accessor and mutator functions for these member variables.
Demonstrate an object of the CustomerData class in a simple program.
#include <iostream>
#include <string>
using namespace std;
class PersonData
{
private:
string lastName;
string firstName;
string address;
string city;
string state;
string zip;
string phone;
public:
void setLastName(string newLastName);
void setFirstName(string newFirstName);
void setAddress(string newAddress);
void setCity(string newCity);
void setState(string newState);
void setZip(string newZip);
void setPhone(string newPhone);
string getLastName();
string getFirstName();
string getAddress();
string getCity();
string getState();
string getZip();
string getPhone();
};
void PersonData::setLastName(string newLastName)
{
lastName = newLastName;
}
void PersonData::setFirstName(string newFirstName)
{
firstName = newFirstName;
}
void PersonData::setAddress(string newAddress)
{
address = newAddress;
}
void PersonData::setCity(string newCity)
{
city = newCity;
}
void PersonData::setState(string newState)
{
state = newState;
}
void PersonData::setZip(string newZip)
{
zip = newZip;
}
void PersonData::setFirstName(string newFirstName)
{
firstName = newFirstName;
}
class CustomerData: public PersonData
{
public:
};
int main()
{
system("pause");
return 0;
}
I'm not really sure where to go from here. Any suggestions or tips would be awesome!
You want to derive a class CustomerData. You can add this code for that class
class CustomerData: public PersonData
{
public:
int customerNumber;
bool mailingList;
static int totalCustomer;
};
int CustomerData :: totalCustomer=0; This code is to initialize the static variable of the class.
You can Write the code to get data by using the prototype defined by you.
In main you can use the object of CustomerData class to access the setters and mutator functions defined in the PersonData class.
for example :
CustomerData obj;
obj.setLastName("XYZ");
and to get the last name you can write
obj.getLastName();
but remember you have to write the getLastName() and all get______() functions.
i am trying to understand how can i access private classes through public classes because some experts said to me that i have to use only private classes. But i can't understand why this doesn't work.I really don't know how can i access private through public its really confusing .
#include <iostream>
#include <string>
using namespace std;
class ManolisClass{
public :
void setName(string x){
name = x;
}
string getName(){
return name;
}
private :
string name;
};
int main()
{
ManolisClass bo;
getline(cin, bo.setName() );
cout << bo.getName();
return 0;
}
Your access methods are correct, but as you can see from the signature of the function setName, you have to provide a string to set the name of the class. getLine method takes a string as argument. You could create an intermediate variable and use that variable to set the name of the class.
Here is how one can do it.
string temp;
getline(cin, temp);
bo.setName(temp);