How can i access attributes from another class with pointer - c++

How can i access the lastname with the pointer in Class 2
class Person
{
public:
Person(string firstname, string lastname);
private:
string firstname;
string lastname;
};
My Class 2
class Account
{
public: Person getPersonName();
private: const Person* person_;
}
.cpp file where lastname should be returned
Person Account::getPersonName()
{
return person_?;
}

You can't access private member of a class outside the class that contain it.
So in this case you can't access them directly.
However you can create a public getter in Person Class for the member lastname and then call it in the Person Account::getPersonName().
In alternative you can define lastname public ( this approch is not recommended ).
Another way is to use friend class. I leave you a useful link:
Friend Class

Related

How to define an Object using inheritance

I have a small problem with a task which was given to us for a preparation for my exam:
In the UML you see the classes. I have to define class Student.
The Constructor I have to define looks like this:
The class Students inherits from interface Immatrikulation and class person.
Also there is a struct for Adresse
In Adresse you can find the string ort (which I have to use in the Constructor) and in "Adresse" you have the string name(also needed)
Student(const string& name, const string& ort, int matrikelnr);
I know how I can access and save data for matrikelnr, since I have the variable in the same class, but i don't know how I can define ort and name for student.
UML
Just call the base class constructor. Following your UML:
class Student : public Person {
public:
Student(const string& name, const string& ort, int matrikeInr) :
Person(name, ort), matrikeINr(matrikeInr)
{ }
// etc...
private:
int matrikeINr;
};

Inheritence in c++

#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.

How do I get private data from the member functions? c++

I am doing the Big c++ 2nd edition questions and I am on classes, I am stuck on a question. Basically I have to classes one called "person" and one called "Pemployee", I need to write the member functions of "Pemployee".
They gave me the declarations I need to implement the definitions.
What I don't get how to do is write call name, since it needs to call the private variable "person_data" which is a person object, I cannot access the string name directly but the member function of "person" has a "get_name" function which returns void, I dont understand how to get a string returned if I cannot return from the other definition.
Here are the two classes.
class Person
{
public:
Person();
Person(string pname, int page);
void get_name() const;
void get_age() const; //returns void
private:
string name;
int age; // 0 if unknown
};
class PEmployee
{
public:
PEmployee();
PEmployee(string employee_name, double initial_salary);
void set_salary(double new_salary);
double get_salary() const;
string get_name() const; //assuming I need to call person get_name
private:
Person person_data;
double salary;
};
So once again, how do I call the "Pemployee" get_name to return the string name of the person_data private variable
Typo in the book, Person::get_name should return string
A lot of programming books teach you to add get and set methods to your classes when the variable needs to be read or modified from outside of the class.
You need to create get methods for each of the private variables that your want value access to outside of the class.
You will need a set methods if you want to change the values from outside the class.
Example get method for your class
std::string get_name() const {return this->name;}
These signatures in the class called Person are pointless:
void get_name() const;
void get_age() const;
It is very probable that it is a typo. If it returned string then it whouldn't be pointless.
However if you would not like to change the functions signature or add a new memeber to the Person, then you should declare PEmployee as friend of Person, so member functions of PEmployee can reach private and protected members of Person. You can see below how to do this.
#include <string>
class PEmployee;
class Person
{
public:
friend PEmployee;
Person(){ }
Person(std::string pname, int page);
void get_name() const;
void get_age() const; //returns void
private:
std::string name;
int age; // 0 if unknown
};
class PEmployee
{
public:
PEmployee();
PEmployee(std::string employee_name, double initial_salary);
void set_salary(double new_salary);
double get_salary() const;
std::string get_name() const; //assuming I need to call person get_name
private:
Person person_data;
double salary;
};

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

C++ Design pattern for separate accessor/mutator interfaces

I have a data structure "Person"
struct Person
{
protected:
string name;
int age;
string address;
...
}
I want to create "views" around this structure to separate out access to different member variables:
class PersonRead: public Person
{
public:
string getName() {..}
int getAge() {...}
...
}
class PersonUpdate: public Person
{
public:
void setAddress( string address_ ) {...}
void setAge( int age_ ) {...}
...
}
I use this to only expose those methods/variables which are really required:
int main()
{
...
writePersonDataToFile ( (PersonRead) personObj );
updatePersonData ( (PersonUpdate) personObj);
...
}
Though the above code serves my purpose, there are several issues including:
The public inheritence here is not exactly an 'is-a' relationship
I need to derive IndianPerson from Person, and all the corresponding interfaces. This leads to bad diamond pattern:
struct IndianPerson: public Person {};
class IndianPersonRead: public IndianPerson, public PersonRead {}; //Person Class common, Diamond pattern here!
Is there a name for such a design pattern? What are better ways to implement this pattern? I have a feeling Policy classes might help, but cant figure out how to implement this
Any examples would be great help
For your scenario this might seem like overkill but, if you want fine grained control over which classes can call different methods on your class the c++ client-attorney idiom idiom might be appropriate.
For a detailed description of this idiom see http://drdobbs.com/184402053
Here is a rough example (note: this has not been compiled, although it is based on production code I am currently using):
class Person
{
public:
/// constructor destructor etc:
private:
string getName() { return name; }
public:
/// Writer Attourney that access to allows class PersonReader access
/// to getXXX functions
class ReaderAttorney
{
private:
/// Add additional reader member functions...
static string readName( Person& p )
{
return p.getName();
}
// Make any classes that shuold be allowde read access friends of the
// attorney here
friend class PersonReader;
};
/// Writer Attourney that access to allows class PersonWriter access
/// to setXXX functions
class WriterAttorney
{
private:
/// Add additiona reader member functions...
static string setName( Person& p, const string& newName )
{
p.setName( newName );
}
friend class PersonWriter;
};
private:
string name;
int age;
string address;
};
This can be used as follows:
void PersonWriter::setPersonDetails( const string& name, int age .... )
{
// PersonWriter is a frend of WriterAttorney and is granted access
Person::WriterAttorney::setName( name );
Person::WriterAttorney::setName( age );
// Note this will fail, since PersonWriter is not a friend of
// ReaderAttorney, ergo it is not granted read permission:
Person::ReaderAttorney::readName();
}
I think that your approach is not correct at all: PersonRead and PersonUpdate are not Persons. They read and modify Person data but are not really Person.
In the same way, IndianPersonRead and IndianPersonUpdate are not an IndianPerson.
I separate this relationship in following:
PersonRead use Person
PersonUpdate use Person
IndianPerson inherits from Person: is a Person
IndianPersonRead inherits from PersonRead and use IndianPerson
IndianPersonUpdate inherits from PersonUpdate and use IndianPerson
I show an example of my apporach:
#include <string>
#include <iostream>
using namespace std;
struct Person
{
string getname() const { return name; }
string getaddress() const { return address; }
void setaddress(const string & address_) { address = address_; }
void setname(const string & name_) { name = name_; }
protected:
string name;
int age;
string address;
};
class PersonRead
{
public:
string getname(const Person & p) { return p.getname(); }
};
class PersonUpdate
{
public:
void setAddress(Person & p, const string & address_ ) {p.setaddress(address_); }
void setname(Person & p, const string & name_ ) {p.setname(name_); }
};
struct IndianPerson : public Person
{
string gettribe() const { return tribe; }
void settribe(const string & tribe_) { tribe = tribe_; }
protected:
string tribe;
};
struct IndianPersonRead : public PersonRead
{
public:
string gettribe(const IndianPerson & p) const { return p.gettribe(); }
};
struct IndianPersonUpdate : public PersonUpdate
{
public:
void settribe(IndianPerson & p, const string & t) { p.settribe(t); }
};
int main(int argc, char **argv)
{
IndianPerson ip;
IndianPersonUpdate ipU;
IndianPersonRead ipR;
ipU.settribe(ip, "Cheroki");
ipU.setname(ip, "Charly");
cout << ipR.getname(ip) << " : " << ipR.gettribe(ip) << endl;
}
First of all I will agree with the Tio's point of view PersonUpdate is not a Person so there is a wrong inheritance usage. Also I believe that you need to make your classes with target to represent the real world so classes like PersonUpdate are wrong because they represent the action and not the object.
In your case one solution could be to use the visitor design pattern, so the Person could accept a especially designed IPersonStream interface in order to perform the serialization in classes which will implement this interface.
Person stream will accept the persons attributes on it or for good the Person's memento take a look on memento design pattern, and serialize it to xml or whatever you want.
I don't have a design pattern name, but to resolve your concerns, I would swap the inheritance relation and let Person inherit from the PersonReader and PersonWriter interfaces. This way, objects that must only read from Person use the PersonReader interface and as such promises to not change it.
By making every member of Person private, you can even make sure that Person is not accessed in another way, but then every class that inherits from Person should have these members private.