C++ friend function not working, private within this context error - c++

I've been doing an exercise for my programming course and the particular one I'm on now is about friend functions/methods/classes. The problem I'm having is that my friend function doesn't seem to be doing it's job; I'm getting "[variable name] is private within this context" errors around my code where I'm trying to access the variables that the friend function should have access to.
Here is the class definition in the header file (I cut out unnecessary stuff to save space).
class Statistics {
private: // The personal data.
PersonalData person;
public:
Statistics();
Statistics(float weightKG, float heightM, char gender);
Statistics(PersonalData person);
virtual ~Statistics();
...
friend bool equalFunctionFriend(Statistics statOne, Statistics statTwo);
friend string trueOrFalseFriend(bool value);
};
Here is the method where the errors are appearing.
bool equalFuntionFriend(Statistics statOne, Statistics statTwo)
{
// Check the height.
if (statOne.person.heightM != statTwo.person.heightM)
return false;
// Check the weight.
if (statOne.person.weightKG != statTwo.person.weightKG)
return false;
// Check the gender.
if (statOne.person.gender != statTwo.person.gender)
return false;
// If the function hasn't returned false til now then all is well.
return true;
}
So, my question is: What am I doing wrong?
EDIT: Problem has been solved by Angew. Seems it was just a typo... Very silly me!

I'm guessing that heightM, weightKG and gender are private to your PersonalData class and this is why you're getting the error. Just because your functions are friends of Statistics, doesn't mean they have access to the internals of the members of Statistics. They only have access to the internals of Statistics. In fact, Statistics itself doesn't even have access to the internals of PersonalData, so its friends certainly don't.
There are a few ways around this. You could make the members of PersonalData public - but that's not a great idea because you will decrease encapsulation. You could make your functions also friends of PersonalData - you might end up with a strange graph of friendships (like Facebook for C++ classes!). Or you could give PersonalData some public interface that allows others to peek at its private data.
As #Angew pointed out in the comments, your function is named equalFuntionFriend when the friend of Statistics is named equalFunctionFriend - you have a missing letter. That would also cause this problem.

Related

Assign object even though assignment operator is implicitly deleted

I'm working on an assignment that uses OMNeT++, Veins/Sumo. Although my question is not completely related to it, it might add some context.
I'm familiar with programming, but having a little bit of trouble wrapping my head around the whole
The idea is that there is a network of cars, and all these cars are talking to eachother using messages. A message inlcudes the vehicle name, but also information about the current position/mobility of the car. This is where TraCIMobilitycomes in.
Ideally I would like to have all this information stored in the original class in the message, but I am running into some issues.
pointer/memory address idea when working with classes.
class InterVehicleMessage : public ::veins::DemoSafetyMessage
{
protected:
::omnetpp::opp_string vehicleName;
veins::TraCIMobility vehicle_mobility; <--- important
private:
void copy(const InterVehicleMessage& other);
protected:
bool operator==(const InterVehicleMessage&);
public:
//stuff
virtual veins::TraCIMobility& getMobility(); <--- important
virtual const veins::TraCIMobility& getMobility() const {return const_cast<InterVehicleMessage*>(this)->getMobility();} <--- important
virtual void setMobility(const veins::TraCIMobility& vehicle_mobility); <--- important
};
This all looks fine and dandy, I assume it functions as intended aswell.
But then when I try to make define the setMobility class I run into some problems.
void InterVehicleMessage::SetMobility(const veins::TraCIMobility& vehicle_mobility)
{
this->vehicle_mobility = vehicle_mobility;
}
This results in the error:
InterVehicleMessage_m.cc:240:28: error: object of type 'veins::TraCIMobility' cannot be assigned because its copy assignment operator is implicitly deleted
I'm not familiar with C++ enough to really know what this means. Is there anyone who could hint me into the right direction?
pastebin to TraCIMobility.h: https://pastebin.com/pGZEepxX
I've decided to save the information necesarry from TraCIMobility in individual variables.
So:
double speed;
veins::Coord position;
veins::Heading direction;
veins::Coord nextPositions[7];
Instead of:
veins::TraCIMobility vehicle_mobility;
As #PaulSanders stated in the comment, this class is not supposed to be copied.
Thanks everyone for their time and effort. Have a nice day.

How to save different objects in C++ where the datatype parameter is encapsulated?

I have two classes as follows, a class named Participant and a class named MainControl.
Some sort of a competition is supposed to take place, the competition is between different participants and is supposed be run through the class MainControl using different methods.
However, now I face a major difficulty that I am unable to solve thus far. This is less of a code problem and more me not being able to understand how execute something.
Basically, I am supposed to be able to print a full list of the competitors and their data, sorted by the state they represent. However, I can't think about a way to save the participants in some sort of a data type that will enable this.
That is because I have some limitations:
-The class Participant has a single constructor, as defined below.
-I can't use friend on functions in Participant.
-The functions defined in MainControl and in Participant are the only functions allowed (this includes external functions as well regarding those classes).
-Arrays are the only datatypes I am able to use, and any other ones will need to be completely defined by me.
If I try to use an array containing participants, I face an error because an array cannot be defined because the class Participants doesn't have the constructor required.
To my understanding there is a way to overcome those limitations defining some sorts of private structs, however I can't understand how to do so, because to me no matter what type of object I define, I won't be able to use it because the parameters are private and I have no get functions.
I am looking for ideas, the two classes are posted below. If there is a way to solve this using arrays I would love to see it.
Ignore code errors as this is not the point.
Can anyone help please?
class Participant
{
// relevant private members can be defined here, if necessary.
string state_name;
string song_name;
int time_length;
string singer_name;
bool is_registered;
public:
Participant(string state, string song, int time, string singer):
state_name(state),song_name(song),singer_name(singer),time_length(time),is_registered(false){
}
~Participant() = default;
string state() const;
string song() const;
int timeLength() const;
string singer() const;
int isRegistered() const;
void update(const string song, const int time, const string singer);
void updateRegistered(const bool status);
};
ostream& operator<<(ostream& os, const Participant& p);
class MainControl
{
// relevant private members can be defined here, if necessary.
int max_time_length;
int max_participants;
int max_votes;
int current_participants;
Phase current_phase;
public:
MainControl(int time_length = DEFAULT_MAX_TIME, int participants = DEFAULT_MAX_PARTICIPANTS, int votes = DEFAULT_MAX_VOTES) : max_time_length(time_length), max_participants(participants), max_votes(votes), current_phase(Registration), current_participants(0){
};
~MainControl();
MainControl& operator+=(const Participant& p);
friend ostream& operator<<(ostream& os, const MainControl& mc);
};

Is there a name for this C++ idiom in which a type vends a wrapper that expands its interface?

I have what is essentially a family of types that share a few common properties with each other. I could actually model this relationship fairly decently with C++ class inheritance. However, I also need to pass and store these objects all around my code, and keeping every instance as a polymorphic heap reference is a pain.
Here's the initial situation:
Enumeration type with values for all "subclasses":
enum class PhoneType {
landline,
cell
}
Type that's stored and passed around a lot:
class Phone {
public:
static Phone landline(PhoneNumber number) {
return Phone(PhoneType::landline, number);
}
static Phone cell(PhoneNumber number, optional<AppList> apps) {
return Phone(PhoneType::cell, number, apps)
}
PhoneType type() { return _type; }
PhoneNumber number() { return _number; }
private:
PhoneType _type;
PhoneNumber _number;
optional<AppList> _apps;
Phone(PhoneType type, PhoneNumber number) :
_type(type), _number(number)
{}
Phone(PhoneType type, PhoneNumber number, optional<AppList> apps) :
_type(type), _number(number), _apps(apps)
{}
};
PhoneType enumerates different possible types of Phones, which all have a PhoneNumber and may or may not have an AppList.
The issue is how to go about giving the outside world access to a phone's AppList once the caller is sure that it's dealing with a cell phone. Note that I don't want to simply vend the optional type, as this pushes a lot of error checking code into the calling function(s), which is not what I want (in the majority of cases, the caller knows the PhoneType of the Phone it's being passed without even having to check, so vending an optional<> is just unnecessary pain).
I could just add the extra accessors to the Phone class, and document that they throw/crash/etc. if the receiving Phone doesn't represent a cell phone. However, in the real code there are many more such attributes that would require more accessors, and each of these accessors is not at all clear about its preconditions when read at a call site.
Long story short, after a bit of consideration I ended up with this idiom:
Before the definition of Phone:
class CheckedPhoneRef {
public:
CheckedPhoneRef() = delete;
Phone& phone() const { return * _phone; }
protected:
Phone* _phone;
CheckedPhoneRef(Phone* phone) : _phone(phone) {}
private:
friend class Phone;
};
class LandlineCheckedPhoneRef : public CheckedPhoneRef {
public:
using CheckedPhoneRef::CheckedPhoneRef;
};
class CellCheckedPhoneRef : public CheckedPhoneRef {
public:
using CheckedPhoneRef::CheckedPhoneRef;
AppList apps() const; // accesses private member of referenced Phone
};
In Phone's public section:
// (Comment above declarations in header):
// These assert that this Phone is of the correct PhoneType.
LandlineCheckedPhoneRef landline_ref() {
assert(_type == PhoneType::landline);
return LandlineCheckedPhoneRef(this);
}
CellCheckedPhoneRef cell_ref() {
assert(_type == PhoneType::cell);
return CellCheckedPhoneRef(this);
}
// (Plus const versions)
In Phone's private section:
friend LandlineCheckedPhoneRef;
friend CellCheckedPhoneRef;
Now it is rather clear what assumptions are being made at any given call site: if I say phone.cell_ref() then I'm clearly asserting that this phone is a cell phone, e.g.,
void call(Phone& phone) {
if (phone.type() == PhoneType::cell) {
if (has_facetime(phone.cell_ref())) ...
} else {
...
}
}
bool has_facetime(CellCheckedPhoneRef cell_phone) {
return cell_phone.apps() ...
}
(Dumb example, but you get the point. I know I could use a visitation pattern here, but the real code isn't quite like this.)
I like this design for what I'm doing. Problem is, I don't quite know what to name the vended wrapper types. I'm currently using the pattern of LandlinePhoneLens, CellPhoneLens, etc., but I know that "lens" already has other meaning in programming. Perhaps this isn't a big issue, but I wanted to ask to be sure I'm not missing a more established naming scheme.
Is there an established name for this pattern/idiom in which a type vends a wrapper that expands its interface?
Your intent is unfortunately not fully clear to me.
At first, I thought that you'd just reinvented the decorator pattern, in which you add dynamically some responsibilities (accessor) to an existing object.
But looking more closely, I think that it all just looks like an anti-pattern, a dependency mess, and a flawed design: eveytime that in the base class you need to be friend of derived class, you should have alarm bells starting to ring.
Instead of looking for a name, you'd better engineer a cleaner design. Forget the enum, and go for an abstract Phone base class, with abstract functions corresponding to what every phone shall be able to do. Then create two derived concrete classes: LandLine and CellPhone, both inheriting from Phone.
Now you could consider that getting the list of apps is a common functionality of all kind of phones, and that a LandLine just returns an empty list. All your code would then just use build in polymorphism to do the job in a proper an extensible way:
If tomorrow, someone would invent a TelepathyPhone, you'd just need to impelement the common functions required by the abstract interface, and all the using code would still work unchanged.
In the worst case, if you'd really need to call a very specific class dependent function that was totally unknown in the common interface (e.g. TelepathyPhone::displayBrainWavelength()), you could go for an if using dynamic_cast. At least you'd avoid to create a new enum everytime you invent a new derived class.

C++ virtual method: best way to use base implementation with an addition

Say I have the following classes:
class Airplane
{
virtual bool Fly(uint64_t destinationID)
{
//Do what an airplane does to be flown.
}
/*
* More function and data members.
*/
}
class SomeModel: public Airplane
{
virtual bool Fly(uint64_t destinationID);
{
//Do something that SomeModel specifically should do before it gets flying.
//Do exactly what Airplane::Fly does.
}
}
My question is how to implement SomeModel::Fly. One simple way is as follows:
virtual bool SomeModel::Fly(uint64_t destinationID)
{
//Do something that SomeModel specifically should do before it gets flying.
Airplane::Fly(destinationID);
}
Is there a nicer way of doing it? Or is there another reason for choosing another way. I know this is a general question but it's the first time I have to implement such a method so I want to make sure I'm not missing anything.
EDIT
I find it worth to emphasize that Airplane is not a general or abstract class, many Airplane in the company are just airplanes and appear as such without any inhritance, there is one specific model though that has some specific behavior.
This really depends on what you are trying to achieve. Your example is certainly valid and one solution to one type of problem (where a some setup or other variations are required early on).
Another variant on this theme is to use a virtual setup, and then a common "fly" method.
So:
class Airplane
{
bool Fly(uint64_t destinationID)
{
SetupForFlight();
// do actual flying stuff
...
...
}
virtual void SetupForFlight() { // do nothing for standard airplane }
}
class Boeing747: public Airplane
{
...
void SetupForFLight()
{
... do stuff that needs to be set up here.
}
...
}
There are benefits with both of these methods, and it will probably depend on what you are modelling which is better.
Of course, you could have a AfterLanding type function at the end of Fly as well.
Just out of curiousity, are there so many destinations that you need a 64-bit value for them - I've never really considered it, just curious.
Edit: I think what I'm describing is a "Template method pattern". I'm not great with names for these things, I just know how it's working....

Sort function which takes a vector of pointers to an interface class

I've recently begun learning c++ (no prior programming knowledge). I've used the book "Jumping into c++" By Alex Allain and i've found it most useful! However i've reached the chapters of classes, inheritence and polymorphism, and while i do understand most of it I just cannot wrap my head around this one problem.
In the book I am asked to solve the following problem:
Implement a sort function that takes a vector of pointers to an interface class, Comparable,
that defines a method, compare(Comparable& other), and returns 0 if the objects are the
same, 1 if the object is greater than other, and -1 if the object is less than other. Create a class
that implements this interface, create several instances, and sort them. If you're looking for
some inspiration for what to create—try a HighScoreElement class that has a name and a
score, and sorts so that the top scores are first, but if two scores are the same, they are sorted
next by name.
I've created the classes Comparable and HighScores:
class Comparable {
public:
virtual int compare(Comparable& other)=0;
};
class HighScore : public Comparable {
public:
HighScore(int, std::string);
virtual int compare(Comparable& other);
private:
int highscore;
std::string name;
};
If i try to overwrite the inherited function in HighScore, i am not able to compare, for instance the int highscore, with the int highscore of (Comparable& other), since i cannot access the other.highscore. Example below:
int HighScore::compare(Comparable& other){
if (highscore == other.highscore) {
return 0;
}
//...
}
I thought i could maybe change the virtual method to something like:
int HighScore::compare(HighScore& other){
if (highscore == other.highscore) {
return 0;
}
//...
}
Since that would allow me to access other.highscore (and i had hoped that i would work since HighScore also can be considered a Comparable. But alas no such luck. What should I do, i litterally have no clue on how to continue and i would appreciate any help i can get. Thanks :)
Indeed, trying to choose behaviour based on the run-time type of two or more objects is a bit fiddly in a single-dispatch language like C++.
The simplest solution is to use RTTI to determine whether the other object has a type comparable with ours:
int HighScore::compare(Comparable& other){
int other_highscore = dynamic_cast<HighScore&>(other).highscore;
if (highscore == other_highscore) {
return 0;
}
//...
}
This will throw an exception if the types aren't comparable, which is probably the best you can do.
Alternatively, you could implement a double-dispatch mechanism (such as the "Visitor Pattern"), involving two virtual functions. I'll let you research it yourself, since an example would be long-winded and not particularly inspiring.
Hopefully, you will soon learn how to do this using compile-time generics rather than run-time abstract interfaces, which is much more idiomatic in C++. If the book doesn't teach you that, throw it away and get one of these instead.
You can write a pulic getter function to get the score
class Comparable {
public:
int get_score() const = 0;
//
}
class HighScore : public Comparable {
public:
int get_score() const { return highscore; }
and then use that for comparison.
int HighScore::compare(Comparable& other){
if (highscore == other.get_score()) {
^^^^^^^^^^^
return 0;
}
//...
}
But since only the derived class has highscore member you should probably change what you pass to compare.
int HighScore::compare(HighScore& other)
OR move highscore member to the base class. Whichever males sense to you.
I'd suggest picking another book on the subject. Since this exercise seemed to be vague and doesn't give good understanding on polymorphism. The tricky part is that when you get Comparable in your compare method you have no clue, if it is HighScore or some other derived class. And in case if the class you are attempting to compare is not an instance of HighScore such terms as equal less and greater doesn't have any meaning. Thus there is no way to solve this correctly. You can of course use dynamic_cast to check if it is HighScore, but still if it doesn't there is no good answer if it greater, lesser or equal to something that isn't a HighScore.
Just imagine that there is something like class Color : public Comparable { exists. What should you return in case if you get Color to be compared with HighScore? Is blue bigger than 10, or Yellow less than 15, what red is equal to?