Friend function can't access private members - c++

I'm trying to get a friend function of class1 and ships to access the private members of both, but it says that those members are inaccessible.
The code is below, the problem is in ships.cpp. I tried to reproduce this problem in an even more simple manner in a single file but it didn't happen there, so I don't know what's wrong here. Maybe it's a circular declaration problem?
ships.h
#ifndef _SHIPS_H_
#define _SHIPS_H_
#include "point.h"
class class1;
class Ships{
public:
friend char* checkpoints();
private:
Point ship[6];
};
#endif // ! _SHIPS_H_
ships.cpp
#include "ships.h"
#include "class1.h"
char* checkpoints(Ships ship, class1 game) {
ship.ship[0];//cannot access private member declared in class 'Ships'
game.smallship;//cannot access private member declared in class 'class1'
return nullptr;
}
class1.h
#ifndef _CLASS1_H_
#define _CLASS1_H_
#include "ships.h"
class class1 {
public:
friend char* checkpoints();
private:
static const int LIVES = 3;
Ships smallship, bigship;
};
#endif

Just making my comment an answer. You declared char* checkpoints() as a friend function. Declare the correct prototype char* checkpoints(Ships ship, class1 game) as a friend instead.
You also probably want to use references (maybe const) otherwise the arguments are passed by value (copy): char* checkpoints(Ships& ship, class1& game)

Related

Friend class in C++ not allowing access to private member attributes

I recently started C++ and to be completely honest my lecturer isn't much help, I am trying to give a linked list friend access to a node class. From what I can see I have declared everything I need, but I still cant access the Node private members , if somebody could see something im missing that would be great!
My node header file:
```#ifndef NodeofBook_h
#define NodeofBook_h
#include <stdio.h>
#include "Book.h"
class ListOfBooks;
//
class NodeofBook {
friend class ListOfBooks;
private:
NodeofBook* next;
Book* theBook;
public:
};
#endif /* NodeofBook_h */
My linked list header file :
#ifndef ListOfBooks_h
#define ListOfBooks_h
#include <stdio.h>
#include "NodeofBook.h"
class ListOfBooks {
private:
public:
ListOfBooks();
void insertBack(int);
void displayList();
int deleteMostRecent();
int deleteInt(int pos);
};
#endif /* ListOfBooks_h */
My Linked List cpp file:
#include "ListOfBooks.h"
int ListOfBooks(){
return 0;
}
ListOfBooks::ListOfBooks(){
theBook->title = "noTitleYet";
theBook->isbn = 0000;
next = NULL;
}
I am getting an error stating Use of undeclared identifier 'theBook'
Any help is really appreciated!
NodeofBook declaring that ListofBooks is a friend class just means that the implementation of ListofBooks can access NodeofBook's private members, but there still needs to be an instance of NodeofBook to access. Its members are not static; non-static member variables are part of some object. That is, just because the ListofBooks is a friend of NodeofBook does not mean that it magically has instances of NodeofBookmembers.
A friend relationship is not an is-a relationship like inheritance: it is just about access.

Multiple accesses of a singleton object in many classes

I have a struct that multiple classes can access and edit. So I created this struct's object as static in class and created a get method.
In Class1.cpp:
#include "Class1.h"
static MyStruct struct;
MyStruct* Class1::get_my_struct()
{
return &struct;
}
I thought of creating this class`s object as a singleton to guarantee that this struct can be accessed through a single object.
In Class2.cpp:
#include "Class2.h" //Class1.h file included in this file.
void Class2::log_value()
{
Class1& singleton_obj_cls1 = Class1::getObject(): //return singleton object
singleton_obj_cls1 .get_my_struct().tempr_val=log_temp_val(); //log this value of struct by class 2 method
}
void Class2::change_value()
{
Class1& singleton_obj_cls1 = Class1::getObject():
//Do I have to get the singleton object for different methods even though they are in the same class?
//Can a singleton object get in one place in class and the whole class use it as a class member?
singleton_obj_cls1 .get_my_struct().tempr_val=45;
singleton_obj_cls1 .get_my_struct().x_val=66 ;
}
I have class 3 class that uses both class1 and class 2.By the way, I changed class2`constructor to a singleton.
In Class3.cpp:
#include "Class3.h" //Both Class1.h and Class2.h file included in this file.
void Class3::calculate_value()
{
Class1& singleton_obj_cls1 = Class1::getObject():
Class2& singleton_obj_cls2 = Class2::getObject():
singleton_obj_cls2.log_value();
singleton_obj_cls1.get_my_struct().pressure_value=300;
}
My third question is, Is there a better design method that you can fix instead of getting singleton objects in multiple places before using each struct or should I create the object once in the top class and give it as parameters to all 100 methods of perhaps 20 different classes that should have access to this struct?
Do I have to get the singleton object for different methods even though they are in the same class?
Can a singleton object get in one place in class and the whole class use it as a class member?
Use a member variable in your header file and initialize it in the constructor member initializer list:
Example Class2.h
#include "Class1.h"
class Class2 {
//...
private: // maybe public/protected to access from other classes
Class1& m_singleton_obj_cls1;
};
Example Class2.cpp
#include "Class2.h"
Class2::Class2()
: m_singleton_obj_cls1(Class1::getObject()) {
}
//...

Issues calling base class function from derived class

I am currently very new to c++, i have started learning how to use pointers in a path finding algorithm.
I am having an issue with calling a function within a class that is derived from a base class.
The specific piece of code causing issue is:
FreeTile *tempPointer = new FreeTile();
cout<<tempPointer->getFree()<<endl;
mapp[i][j] = tempPointer;
when i call getFree (which returns a boolean value) i get the error:
undefined reference to Tile::getFree(). Tile being the base class.
The header for FreeTile is:
#ifndef FREETILE_H
#define FREETILE_H
#include "Tile.h"
class FreeTile:public Tile
{
public:
FreeTile();
virtual ~FreeTile();
void setParent(FreeTile* par);
int getF();
int getG();
int getH();
void setF(int in);
void setG(int in);
void setH(int in);
FreeTile* getParent();
protected:
private:
int F;
int G;
int H;
bool free;
};
Tile header is:
#ifndef TILE_H
#define TILE_H
class Tile
{
public:
Tile();
virtual ~Tile();
bool getFree();
void setFree(bool bo);
protected:
private:
bool free;
};
#endif // TILE_H
#endif // FREETILE_H
Finally the cpp file for Tile:
#include "Tile.h"
#include <iostream>
using namespace std;
bool free;
Tile::Tile()
{
cout<<"Constructor Called"<<endl;
}
Tile::~Tile()
{
//dtor
}
bool getFree(){
return free;
}
void setFree(bool bo){
free = bo;
}
If you need more code or if im missing something blatant feel free to shame me as much as you like :P
Thanks in advance.
On a side note, can you initiate a private variable in a constructor such as free = true as when doing this it states the variable is private.
In the Cpp file rename "bool getFree()" to
"bool Tile::getFree()"
In your implementation the function is just a regular c gloabl function.
In the fixed version it is the class function implementaion of the function you declare in the header file
Also
1st in your Tile you have a private variable "bool free"
in the cpp file you have a global variable "bool free"
this is confusing.
Probably want to delete the one you declared in the cpp file.
Want a deeper explanation?
Yeah! my 1st answer!
Deeper Explanation:
the function you declared in the Class Tile is not defined (just declared) because you didn't add "Tile::" before the function definition in the cpp file (i.e you didn't define a scope).
The function you wrote in the cpp file is both defined and declared in the cpp file, so only functions written after it in the cpp file can call it (works same a c).
Probably when you wrote the function it didn't know that "free" was, right? because it was not a class function. so you added the global "bool free" but that is a completely different variable.
Glad to help!
don't forget to mark this as answered!

C++ Error: use of undefined type

I have two classes, Friend2 is a friend of Friend1. After Friend2 accesses the Friend1's private member variable, I want Friend1 to be able to access the Friend2's public member functions. So I decided to use composition inside Friend1. However, the compiler shows me the error:
use of undefined type 'friend2'
Then, I tried another way, making Friend1 a friend of Friend2 too. But I still got the same error. Would anyone teach me the way to solve? Thx a lot!
#ifndef FRIEND1_H
#define FRIEND1_H
class friend2;
class friend1 {
private:
int x;
public:
friend1();
int comp(friend2* f2o);
friend class friend2;
};
friend1::friend1() {
x = 1;
}
int friend1::comp(friend2* f2o) {
return f2o->getxx(); //the error : use of undefined type
}
#endif
#ifndef FRIEND2_H
#define FRIEND2_H
#include "friend1.h"
#include <iostream>
class friend2 {
private:
int xx;
public:
friend2();
void p(friend1* f1o);
int getxx() const;
friend class friend1;
};
friend2::friend2() {}
void friend2::p(friend1* f1o) {
xx = f1o->x;
}
int friend2::getxx() const {
return xx;
}
#endif
Also, is composition or friend class the better way to do this? Why?
You get //the error : use of undefined type because class Friend2 is only declared, not defined at that point. To solve this move int friend1::comp(friend2* f2o) implementation to friend1.cpp and include friend2.h from there.
UPDATE In general, if two classes are mutual friends (and even if only one of them is a friend to another), it's a good reason to think about the design.

How can a class A, that is a member of class B, share private members of class B?

I have the following code:
Master.h
#ifndef MASTER_H
#define MASTER_H
class Master
{
friend class Friend;
public:
Master(void);
~Master(void);
void CallFriendFunction(int largeData);
private:
int largeData;
//Want this class to share largeData;
Friend testFriend;
};
#endif // MASTER_H
Master.cpp
#include "Master.h"
Master::Master(void)
{
//Inentionally left blank
}
Master::~Master(void)
{
//Intentionally left blank
}
void Master::CallFriendFunction(int largeData)
{
this->largeData = largeData;
this->testFriend.Test(this);
}
Friend.h
#ifndef FRIEND_H
#define FRIEND_H
#include "Master.h"
class Friend
{
public:
Friend(void);
~Friend(void);
void Test(Master* masterPtr);
};
#endif // FRIEND_H
Friend.cpp
#include "Friend.h"
#include <iostream>
Friend::Friend(void)
{
//Intentionally left blank
}
Friend::~Friend(void)
{
//Intentionally left blank
}
void Friend::Test(Master* masterPtr)
{
std::cout << masterPtr->largeData << std::endl;
}
I want class Friend to be able to share Master's private members. However, I can't get this code to compile. I've tried Forward Declaration, and #includes, but I start getting into circular dependencies. When Friend class is not a member of Master class, the code compiles?
Is it possible for Friend class be a member of Master and be friends?
How else can Friend class have access to Masters private members?
You need the following includes and forward declarations:
In Master.h:
#include "Friend.h"
In Friend.h:
class Master;
In Friend.cpp:
#include "Master.h"
Putting the forward declaration in Friend.h prevents circular dependency. A forward declaration is enough there because you only declare a Master* parameter, without using its members yet.
You do need to include Friend.h from Master.h because you are declaring a Friend member, and this requires a complete type.
It looks like you're struggling with circular dependencies. Note that, to make something a friend you do not need to include it. That said, in your Master class, you instantiate friend which requires its inclusion as a header (otherwise the compiler will be all WTF?).
However, in friend.h you can simply forward-declare the master class and not directly include it:
class Master;
This is because you are not attempting to instantiate the Master class, but use a pointer to it.