Classes, Privates through Publics - c++

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);

Related

Extending built-in classes in C++

I know extending built-in classes in C++ is deprecated, but still I want to do it for some reasons.
I wanna add my custom methods to a class (str) that extends/inherits from the std::string class (this is for an example)
But when I do so there's some problem I am facing with the methods that are already there in the std::string class (built-in methods), for example,
#include <bits/stdc++.h>
using namespace std;
class str : public string {
public:
string s;
str(string s1) {
s = s1; //ig the problem is here
}
};
int main() {
str s("hello world");
cout << s.size(); //prints out 0 not 11 => length of "hello world"
}
How do I get around this?
std::string doesn't know about your string s; member. It cannot possibly use it in its methods. If you want to use inheritance over composition, you need to use whatever is available under public interface of std::string - in this case, its constructors.
class str : public string {
public:
str(string s1): string(s1) //initialize base class using its constructor
{
}
};
// or
class str : public string {
public:
using string::string; //bring all std::string constructors into your class
};
As a footnote, there is nothing deprecated about inheriting from standard containers, but they are not meant for that and you can only do a very limited set of things safely. For example, this is Undefined Behaviour:
std::string* s = new str("asdf");
delete s; // UB!
More detailed explanation in this question.
Also, you should strongly avoid <bits/stdc++.h> and using namespace std; and in particular you should not mix them. You will strip yourself of almost every name and it produces hard to find bugs.

How to access private class members with out being in the in class [duplicate]

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?

compilation error due to private variable declaration inehritance

I get the following error compiling the code below:
Student.cpp:20:9: error: ‘std::string Student::name’ is private within this context
20 | name = _name;
| ^~~~
Student.cpp:7:12: note: declared private here
7 | string name;
#include <iostream>
using namespace std;
class Student
{
private:
string name;
};
class UndergraduateStudent : public Student
{
};
class GraduateStudent : public Student
{
};
class Freshman : public UndergraduateStudent
{
Freshman(string _name)
{
name = _name;
}
};
What could be the reason for this?
I want to keep UndergraduateStudent class as abstract
I had a hard time understanding public, private, and protected when I was learning object-oriented programming in C++, and thought that I would share a few thoughts to hopefully clear some of this up.
First of all, public, private, and protected are used to determine the level of accessibility of a variable or method in a class. If you declare a variable as private, you can access that variable inside of the class that it was declared in, but nowhere else. With protected, you may access that variable in the child classes of the class it was declared in. And with public, you can access that variable anywhere.
So what does this mean?
Using your code, we start off with this:
#include <iostream>
using namespace std;
class Student
{
private:
string name;
};
class UndergraduateStudent : public Student
{
};
class GraduateStudent : public Student
{
};
class Freshman : public UndergraduateStudent
{
Freshman(string _name)
{
name = _name;
}
};
The reason that you got a compile error is that you tried to access the variable "name" in the Freshman class. Freshman is a child class of Student (well, it's actually a child class of Undergraduate Student which is a child of student, but the concept still applies). Because of this, any method in the Freshman class will only be able to access protected and public variables and methods in the Student class. Therefore, if you want to access "name" in the Freshman class, you must change it from private to either protected or public.
However, after doing this, you might wonder how to access private and protected variables from outside of the class? In main() how would you get the value of a freshman's name if it is private or protected? The answer to this is getters and setters. Modifying your code a little bit, you get something like this:
#include <iostream>
using namespace std;
class Student
{
protected:
string name;
public:
string getName(){
return name;
}
void setName(string _name){
name = _name;
}
};
class UndergraduateStudent : public Student
{
};
class GraduateStudent : public Student
{
};
class Freshman : public UndergraduateStudent
{
public:
Freshman(){}
Freshman(string _name)
{
name = _name;
}
};
As you can see, I added a couple of public methods in Student, getName() and setName(). I also added some constructors in the Freshman class. The important part about these Student methods is that they are public, and can be accessed anywhere. It's not difficult code to understand, essentially getName() returns the value of the private variable "name", and setName() is able to change that value.
So lets say that in main() I wanted to create a Freshman object, and declare her name as Sarah, and print out that result.
int main(){
Freshman freshman("Sarah");
cout << freshman.name;
}
If I did this, I would get a compile error, because I am trying to access the protected variable "name". If I wanted to access the value, I would have to access it through the public method getName(). Therefore:
int main(){
Freshman freshman("Sarah");
cout << freshman.getName();
}
This would print out the correct result of "Sarah". Now, let's say that I spelled her name wrong, and it turns out there's no 'h' in her name. Then, I would have to call the public method of setName in order to change her name to something else.
int main(){
Freshman freshman("Sarah");
freshman.setName("Sara");
cout << freshman.getName();
}
This would now output the value of "Sara". These are just some basic examples of how to use private, protected, and public, sorry if it was a little bit lengthy. I hope that it can help you if you don't quite understand exactly how to use them yet. Just practice, it comes after doing it a few times.

Cin and cout in a constructor

I'm told to read a name from a constructor (homework), however the class constructor is not supposed to take any parameters - something I find weird.
I have tried to simply put cout's and cin.getline's inside the constructor, butt that doesn't work. I don't get how I can read data from user inside a constructor that does not have any parameters. Is it even possible?
E.g
class Animal
{
private:
char name[20];
public:
Animal() { SOMEHOW READ NAME HERE WITHOUT CON. PARAMETER }
};
int main() {
Animal a1; // should ask for name and read it, add it to data
return 0;
}
#include <iostream>
#include <sstream>
class Animal
{
public:
Animal() : name()
{
// Not the best design approach.Just show it possible for the question.
std::cout << "Name of animal?" << std::endl;
std::getline(std::cin, name);
std::cout << name << std::endl;
}
private:
std::string name;
};
int main(int argc, char * argv[])
{
Animal a1; // should ask for name and read it, add it to data
return 0;
}
I believe the code below is self explanatory with comments to guide you. In object oriented, a class should contain setter and getter methods. I have created a class Animal with one private string variable name. In the constructor, I ask for a name and assign it to the name variable of the object which is being created. I then display the name using a method called getName() which returns the current object's name and it is also known as a getter method. I believe you are new to Object Oriented and I hope I have made these concepts understandable to you.
#include <iostream>
using namespace std;
class Animal
{
private:string name;
public: Animal() {
cout<<"Enter the animal's name?";
getline(cin,this->name); //sets the current obj's name (storing the value)
cout<<"The animal's name is "<<getName();
}
public: string getName(){ return this->name; } //return current obj's name value (getter method)
};
int main()
{
Animal a1;
//cout<<a1.getName(); //it will get the name of a1's object
return 0;
}
#include <iostream>
using namespace std; //Don't kill me
class animal
{
private:
char name [20];
public:
animal () //Constructor without parameters
{
cout<<"Please enter animal name: ";
cin>>name;
}
void getAnimal();
};
void animal :: getAnimal()
{
cout<<name;
}
int main ()
{
animal a1;
a1.getAnimal();
}
Remember that there are 3 types of constructors. In this case it seems that you have to use a default constructor which does require a parameter as it is just setting name to a default value. To get a user defined value you can use cin within the constructor. When you create an object in main and run your program it will allow the user to enter a name.
To read and print the name I found that a getter method was easier.
https://www.geeksforgeeks.org/constructors-c/

Classes with private member .. What is wrong with this code?

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
};