how to access prviate members of an instance in c++, [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I get error when tring to access a private member of a class. My aim was to create a class, make an object and then access what was inputted into it.
So I created a User1.hpp file for my declarations.
class user1 {
private:
string username1;
string email;
string mobile;
public:
user1(string Myfirstname , string emailaddress , string mobile); //constructor
};
In my User1.cpp file, I implemented the class
user1::user1(string Myfirstname , string emailaddress , string mobile)
{
user1::username1 = Myfirstname;
user1::email = emailaddress;
}
then in main.cpp I created the first object and inputted some random data.
user1 firstman {"John" , "john1#email.com" , "011000000"};
Now when I want to see what 'firstman's email was in main.cpp, I tried this:
cout<<"Created "<< firstman.username1 <<" !"<<endl;
Which gives me the error of a private member. What is the best approach to accessing that data?

Private members are meant to be inaccessible from outside the class. You could make username1 public and const:
#include <iostream>
#include <string>
class user1 {
public:
const std::string username1;
user1(std::string Myfirstname, std::string emailaddress, std::string); //constructor
private:
std::string email;
std::string mobile;
};
user1::user1(std::string Myfirstname, std::string emailaddress, std::string): username1(Myfirstname), email(emailaddress) {}
int main() {
user1 firstman {"John" , "john1#email.com" , "011000000"};
std::cout << "Created " << firstman.username1 << " !\n";
}

Related

Retrieve element from list of Object in cpp [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want to retrieve each element from the list of object in cpp and we have classes like below:
class User{
public:
bool isAvailable;
string value;
};
class Users{
public:
User dateFrom;
User dateTo;
User add1;
User add2;
};
Now somewhere else I have created a list of objects of User like std:: list<User> user-list, stored data and then pushback to the list of the object now I want to get that particular data like dateFrom,dateTo, etc.
user-list.push_back(dateFrom);
user-list.push_back(dateTo);
Now I want to access the element of user-list like what we access in list l1 by index like.
This is just a guess of what you might want:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class User {
public:
bool isAvailable;
string value;
};
int main()
{
User someuser;
someuser.value = "Some user";
someuser.isAvailable = true;
User someotheruser;
someotheruser.value = "Some other user";
someotheruser.isAvailable = true;
std::vector<User> user_list; // <<<< using std::vector here
user_list.push_back(someotheruser);
user_list.push_back(someuser);
cout << user_list[0].value << "\n";
cout << user_list[1].value << "\n";
}
We use a std::vector here instead of a std::list because you mention you wanted to access the elements of the list via an index.
Output is:
Some other user
Some user
Disclaimer: This code is still very poor, for example there are no constructors whatsoever.

Passing arguments to objects in C++ - Please explain the logic behind this? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I started learning C++ and now I am lost, I don't see the logic in this. simply does not make sense to me how it is possible that I can add arguments to an object and then those arguments are used by the program. Sure I can memorize this feature, but can someone please explain the logic behind this? Everything else in C++ makes sense, I guess this probably does too, only I don't see it.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Person{
private:
string name;
int age;
public:
Person(){
name = "undefined";
age = 0;
};
Person(string newname){
name = newname;
age = 0;
};
Person(string newname, int newage){
name = newname;
age = newage;
};
string toString(){
stringstream ss;
ss << "Name is: " << name << " Age is : " << age;
return ss.str();
};
};
int main()
{
Person person1;
Person person2("David"); // I don't get this ???
Person person3("Mia", 35); // // I don't get this ???
cout << person1.toString() << endl;
cout << person2.toString() << endl;
cout << person3.toString() << endl;
return 0;
};
You are actually calling the constructors when you say you're passing arguments to objects. Constructors with matching signatures are called.
When you write Person person1;, default constructor which is
Person(){
name = "undefined";
age = 0;
};
is called.
When you write Person person2("David");,
Person(string newname){
name = newname;
age = 0;
};
is called.
And finally, when you do Person person3("Mia", 35);,
Person(string newname, int newage){
name = newname;
age = newage;
};
is called.
This statement: Person person1; is calling this constructor:
Person();
This Person person2("David"); is calling this constructor:
Person(string newname);
And this Person person3("Mia", 35); is calling this constructor:
Person(string newname, int newage);
Since constructors are functions that initialize the object of class Person, they can receive arguments, like any function.
When you define a new C++ class, with its members as your choice, each one of these functions as a regular variable (or pointers, or instances of other classes, etc.) which is a concept you are already familiar with.
So when you instantiate a new instance of the class, the compiler knows exactly how much memory it should allocate, and what is the inner structure of it - how to divide that memory into smaller pieces corresponding to the class members.
And that is how, when you call a constructor, it knows how to "add the arguments" to your instance.

How to solve this print output in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I had the below C++ question in the recent interview but could not do. Please help.
Given a company structure where every employee reports to a superior, all the way up to the CEO, how would you print out all the employees that a particular individual oversees?
Write a method that implements this, given the below:
// Employee object contains a string denoting the.
// employee name, and an array containing
// employees who report to this employee
Employee {
String name;
Employee[] employees;
}
I have seen and understand the recursive function. But I have not encounter such a recursive object/structure like this one.
My new question is how can an object is created and initialized from this class/structure since it is recursive?
Thank you very much again.
With the information given it is very hard to answer (and question should probably be set on hold). Anyway...
I think a recursive approach is the answer. You need a function that can take a name, search the full employee list for that name and then call the function again for every employee in the local array. Something like:
void doit(Employee& e)
{
// Print e.name
// For each employee tmp in e.employees (i.e. local array)
doit(tmp);
}
Note - this requires that there are no loops in manager-employee arrays. If there is this will be an endless loop. So this is a dangerous approach.
EDIT:
This is added due to the comment from OP.
As indicated above the question is vague and doesn't really give sufficient information to provide a good answer. The struct given in the question is not valid C++ and there is no description of how the company wide list of employees are maintained.
However to keep it simple, the printing could look like this:
struct Employee
{
void PrintAllReportingEmployee(int level)
{
cout << string(4*level, ' ') << name << endl;
level++;
for (auto& e : employeesDirectlyReportingToThisEmployee)
{
e.PrintAllReportingEmployee(level);
}
}
string name;
vector<Employee> employeesDirectlyReportingToThisEmployee;
};
// Code in some print function:
// Step 1 - find the relevant employee
Employee tmp = SomeFunctionReturningAnEmployeeBasedOnName("NameOfPerson");
// Step 2 - print all employees reporting directly and indirectly
tmp.PrintAllReportingEmployee(0);
This assumes a single top-level Employee (e.g. director) with a vector of employees directly reporting to the director. Each of these would then have a vector of employees reporting to them and so. So it is kind of an tree structure.
Note, if I should design a employee db, I would not go with such a solution.
Who ever asked the question was looking for an answer with something to do with class inheritance. So a class Persion is extended by Employee where Person is also extended by Manager etc etc where they all share some similar properties but not everything.
This means that your code can be expanded upon by other programmers and one change can fix many different classes!
Although this code does not demonstrate class inheritance, it will work.
/*
THE OUTPUT:
Jacobs-MacBook-Pro:~ jacob$ ./employee
Foo McGoo
Bar Too
Jacobs-MacBook-Pro:~ jacob$
*/
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::endl;
/* define class (this should be in a header file) */
class Employee{
public:
//Variables
string Name;
//Functions
Employee(const string&); //constructor
void AddCoWorker(const Employee&);
void ShowCoWorkers();
private:
vector<Employee> employees;
}; //Note the semicolon
//Entry point
int main(int argc, char **argv){
Employee foo("Foo McGoo");
Employee bar("Bar Too");
Employee me("Bevis");
me.AddCoWorker(foo);
me.AddCoWorker(bar);
me.ShowCoWorkers();
return 0;
}
//Class functions (should be in a separate cpp file)
Employee::Employee(const string& name){
this->Name = name;
}
void Employee::AddCoWorker(const Employee &e){
this->employees.push_back(e);
}
void Employee::ShowCoWorkers(){
int count = this->employees.size();
for(int i = 0; i < count; i++){
//Print the names of each co worker on separate lines
cout << this->employees[i].Name << endl;
}
}

What is the purpose of set here? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
class person
{
private:
string name;
int birth_year;
char sex;
public:
person()
{
string name; cout<<"Name: "; cin>>name; set_name(name);
int birth_year; cout<<"Birth year: "; cin>>birth_year; set_birth_year(birth_year);
char sex; cout<<"Sex: "; cin>>sex; set_sex(sex);
}
~person() { }
what does set_name(name) do here?
I think that set_nume is a member function of the class that sets data member nume of the class (of an object of the class) to the value of local variable nume(that is entered by the user) passed as an argument of the function. Maybe this member function does some checks of the validaty of nume. For example the function could convert the first letter of nume to upper case and all other letters to lower case and so on. You should look through the function that to see what it does (it can simply set data member nume to argument nume like this->nume = nume). Usually such member functions are called as setters. They have the public access control and allow to set private data members of a class.

cpp multidimensional vector [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to store theses string vectors as a 4 dimensional vector. It has been three days that I am searching and I can not decide wether use multidimensional vector,boost multi array ,array of struct ,...
I am so new to cpp and they are so confusing.
vector < string >ID;
vector < string > firstName;
vector < string > lastName;
vector < string > address;
vector<vector<vector<vector<string> >>> person ;
what should I do for populating person ?
As suggested by #hansmaad
The following would be a simpler and better implementation(compared to mulch-dimensional vectors) for storing personal details in your program.
Define a person as:
struct person {
std::string id;
std::string first_name;
std::string last_name;
std::string address;
};
And define your vector as:
std::vector< person > people;
In your case, there is no point in creating multidimensional array. I'd rather try:
class Person
{
public:
string Id;
string firstName;
string lastName;
string address;
};
(...)
vector<Person> People;
// Adding
Person p;
p.Id = "1234";
People.push_back(p);
// Count
std::cout << "Currently you have " << People.size() << " people in the database";
// Access
Person p1 = People[0];
Edit: In response to comments
It's quite tough to answer the question without some specifics about your problem. From what little I know about it, I'd probably go into multi-class version:
class Id
{
public:
int Value;
std::vector<FirstName> Names;
}
class FirstName
{
public:
string Value;
std::vector<SecondName> SecondNames;
}
class SecondName
{
public:
string Value;
std::vector<Address> Addresses;
}
class Address
{
public:
string Value;
}
structure of arrays may be ! Or for a better readable and changeable code use a class