I would like to know if a friend function can change private data in the class without using a
pointer and sending out the object.
I mean does a friend function have access like a member function?
For Example:
class myinfo {
private:
char name[20];
int id;
float income;
public:
void showInfo(void);
myinfo(void);
friend void updateInfo(myinfo);
int main ( ) {
myinfo j;
updateInfo(j); // calling the friend function
return 0;
}
void updateInfo(myinfo c) {
strcat(c.name, ":updated");
c.id++;
c.income += 1.1;
Yes, but not the way you've written it... If you want the function to modify the passed in object, accept a reference rather than by value...
It appears you've not learned about references in c++.
// Declaration of function in class
friend void updateInfo(myinfo&);
implementation
void updateInfo(myinfo& c)
{
strcat(c.name, ":updated"); // now modifying passed in instance of c.
c.id++;
c.income += 1.1;
}
Btw. on a side note, prefer to use std::string and also learn about rule of three (specially for non-trivial classes such as this).
Yes, In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends.
Friends are functions or classes declared with the friend keyword.
If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend.
See it here - http://www.cplusplus.com/doc/tutorial/inheritance/
Related
I have a class defined in header file as below:
// picture.hpp:
class Picture {
public:
int count;
void draw();
};
Corresponding implementing source file:
// picture.cpp
import "picture.hpp";
Picture::draw() {
// some code
someFunction();
}
void someFunction() {
//some code
// can I use variable "count" declared in Picture class in this function
}
Can someFunction() access members of Class Picture?
As your title says you want to access members of class from outside.There may be many ways out there. Like: making class member vaiable & function both static then call it without creating instances of class even if it is private.see-reference
But if you don't want to make member function static and use class member variable from outside,then you may use friend function.Now what friend function can do? you can read it from wikipedia or a blog or might be from here whatever suits your expectation.Now if you use friend function,you have to specify inside your class.like this
class Picture
{
public:
int count;
void draw(Picture obj);
friend void someFunction(/*other parameters if you have*/Picture obj); //as global friend
};
you can perform operations of your member variable inside somefunction() like this:
void someFunction(/*other parameters if you have*/ Picture obj)
{
//some code
// can I use variable "count" declared in Picture class in this function
printf("%d", obj.count);
return;
}
Here comes the design level problem. According to your code,you want to call somefunction() inside of your member function draw() but now somefunction() requires an object as parameter.So it can be done if you pass object in draw() member function.like this:
void Picture::draw(/*other parameters if you have*/ Picture objA)
{
// some code
someFunction(/*other parameters if you have*/ objA);
}
At last,call main function.like this:
int main()
{
Picture pic1;
pic1.draw(pic1);
return 0;
}
Now without creating instances you can not call outside the member of class(except static) [see reference] So,Here two things i have done,i have passed all parameter as 'pass by value' and made somefunction() as friend of that class. Now you have the option to ignore the above whole process as you declared count variable as public. So,use it anywhere inside your class member function just using instance & dot operator but if you desparate to use member variable outside of the class then above process might help you.
Let me know if it helps you or not.
In a file named maze.hpp (a header file) I have the following:
class Maze
{
public:
Maze(int size);
~Maze() {}
void step();
private:
int exitRow;
};
In another file named maze.cpp I have the following:
void step(){
this.exitRow = 3;
}
int main(){
Maze maze(4);
maze.step();
}
This gives an error: invalid use of 'this' outside of a non-static member function
step is a member function of Maze. How can I access the data members of an instance of Maze from within one of its member functions?
When you define a function outside of the class declaration, you are required to provide the class name like this:
void Maze::step(){
exitRow = 3;
}
The compiler has no other way of knowing where the method that you're defining belongs.
Note that there is no need to use this when referring to members from a member function. this is still available and technically writing something like the following is valid: this->exitRow = 3;, but unnecessary. Also, this is a pointer (hence the usage of operator -> rather than .).
The lines
void step(){
this.exitRow = 3;
}
define a global function, not a member function of Maze. Also, this.exitRow is the wrong syntax. You need:
void Maze::step(){
this->exitRow = 3;
}
Your function definition should be:
void Maze::step()
{
}
The way it is now, it just defines a free standing function that does not belong to any class.
Also, this is a pointer so you need to access members by dereferencing it using ->. And it is good to note that you do not need to use this->exitRow to refer exitRow, merely mentioning exitRow inside the member function will serve the same purpose.
I am trying to do this C++ tutorial. I am a beginner in C++ programming. I don't get why they use setValue and getValue in class Class1 and not setClass1. In the other tutorial they use setA and getA in the class class Class1. Here are the codes:
class Class1 {
int i;
public:
void setValue( int value ) { i = value; }
int getValue() { return i; }
};
the second code is:
class A{
int ia;
public:// accessor method because they are used to access a private date member
void setA ( const int a);
int getA ()const;
int getA ();
};
Please help...
The names are arbitrary, you can use any function names you wish (subject to language rules, of course).
However, although you can use xyzzy() and plugh() as getter and setter, it's not really a good idea.
You should use something that indicates the intent of the call, such as getTemperature() or setVelocity(). And these don't even have to map one-to-one to internal fields since encapsulation means the internal details should not be exposed.
By that, I mean you may have a getTemperatureC() for returning the temperature in Celsius even though the internal field is stored as Kelvins:
double getTemperatureC(void) { return kelvins - 273.15; }
void setTemperatureC(double t) { kelvins = t + 273.15; }
(or a getter/setter may use arbitrarily complex calculations).
Using getA() for a class A may well cause you trouble when you create class B to inherit from A but this is outside the scope of the language. But it's good programming practice to follow the guideline above (functions should indicate intent rather than internals).
I was confused on why they use the same name in get and set with the class name, and different get and set name on the other class. Will the set and get names affect the code?
The answer is No.
getter and setter are usually called accessor and mutators in a class. They are just member functions named according to some convention, easy for people who read the code to understand the purpose of those functions, so it is like common sense to name those member function starting with get if you try to access the member variables and starting with set if you try to change some member variables. The names can be any valid identifier.
So setValue or setA are just identifiers for those member functions. It will not affect the code.
Meanwhile, different class can have the same named getter or setters since those function names are in different class scope.
I'd like to know if there's any way to access a private member of a class from outside the class. I'll explain my problem.
I have a .hpp file which contains the definition of the class along with its private members and public function (which are the only one I'd like to export). In the corrisponding .cpp I have to use some "support" function which need access to the private members of the class defined in the .hpp.
Here's part of my code:
--- .hpp ---
namespace vision {
class CameraAcquisition {
/* MEMBERS */
CvSize size;
CvCapture *device;
CvScalar hsv_min,hsv_min2,hsv_max,hsv_max2;
/* METHODS */
public:
CameraAcquisition();
~CameraAcquisition();
int findBall();
};
}
--- .cpp ---
#include "CameraAcquisition.hpp"
using namespace vision;
IplImage *grabFrame() {
// code here
}
IplImage *convertToHSV(IplImage *origin) {
// code here
}
IplImage *calculateThresholdedImage(IplImage *converted) {
// code here
}
What I need is for these three functions to access the members of the class CameraAcquisition. Is there any way to do it? Any suggestions will be appreciated. Thank you all
EDIT
Sorry, I forgot an important piece of information here. In the source file, findBall() must call those methods. I defined those methods to make the code easier to read. I cannot declare those methods in the class definition because I don't want to export them.
If I declare them in a "private" block everything works fine, but maybe it's not correct to that (I don't see the point in providing an header file with private methods.
If those members are made private and you need access to them, you're doing something wrong, so my suggestion is that you don't.
Now let's get serious - there are some ways - DISCLAIMER: not all are safe or portable or guaranteed to work:
1) Preprocessor abuse
#define class struct
#define private public
#include "CameraAcquisition.h"
#undef class
#undef private
2) Fake class
class MyCameraAcquisition {
public: //<--- public in your class
/* MEMBERS */
CvSize size;
CvCapture *device;
CvScalar hsv_min,hsv_min2,hsv_max,hsv_max2;
/* METHODS */
public:
CameraAcquisition();
~CameraAcquisition();
int findBall();
};
CameraAcquisition prvt;
MyCameraAcquisition publ = (MyCameraAcquisition&) prvt;
3) Template abuse posted by litb - http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
This one is, actually, and surprisingly, standard-compliant.
You should not want to access private mebers of objects. Consider providing public getter/setter member functions that outside code can use to affect the private member variables
Alternatively, you can make your support function a member of the class, so it has automatic access to the private members.
If you really want to access private members, you can use the friend keyword to declare another class or function as friend of the current class
class A
{
int a; // private
friend class B;
friend void f(A*);
};
Here both class B (i.e. its member functions) and free function f can access A::a
Use getters in your CameraAcquisition class
i.e.
CVSize getSize() { return size; }
CvCapture* getDevice { return device; }
etc...
You could always declare them as friends by adding in the class definition:
friend IplImage * ::grabFrame();
Compiler used is Visual Studio 2015
This method is not recommended but works.
Lets consider following class
class mydata
{
private:
int x;
public:
mydata(int no)
{
x=no;
}
}
Only data members are stored in the class object.
Now I can access the x using following function.
As I know that class mydata has only one variable it must be the int x.
int getx(mydata *d)
{
return ((int*)d)[0];
/*
How did this work?
-> d is pointing to the mydata object.
as I typecasted it to int* it will be considered as int array.
Of that array (which has lenght 1) access the first element.
*/
}
If there was another variable lets say y of type DATATYPE.
Now, to access y we have to calculate the offset of it from the base of object.
Usually data is stored in the same order in which you declare it.
Also, there is struct padding to be considered in case of heterogeneous data types in the class.
I would like to suggest you to read struct padding in depth.
And the we can get y as
myclass *ptr =new myclass();
int offset_y=//whatever offset of y in number of bytes from base of object of perticular class;
char *byte_ptr_y=((char*)ptr)[offset_y];
DATATYPE y=*((DATATYPE*)byte_ptr_y);
Hello to all that read
I am self learning C++ from a text book:
A Question in the textbook asks me to make a function a friend of a class and therefore the friend function can have access to all of the classes members; which is fine I can do this.
Problem is that the question then goes on to ask that the friend function can only read the class members (private members) but NOT write to them!
**Please note: I have looked at similar question/answers on 'stackoverflow' - but I could not find the relevant and simple straight forward answer that I am after.
Here is some relevant code that I have, any help would be appreciated:
Many thanks in advance
#include <iostream>
#include <cstdio>
using namespace std;
class classroom{
private:
char name[25];
int student_id;
float grades[10];
float average;
int num_tests;
float letter_grade;
static int last_student_id;
public:
void enter_name_id(void);
void enter_grade(void);
void average_grades(void);
void letter_grades(void);
void output_name_id_grade(void);
void last_id(void);
classroom();
friend void readers(classroom&);
};
int classroom::last_student_id=1;
void readers(classroom& lee){
cout<<"\n number tests: "<<lee.num_tests;//friend function is reading class member -This is O.K!
lee.num_tests=15;//friend function is writing to class member - We don't want this to be allowed
cout<<"\n number tests: "<<lee.num_tests;//Used to test that class members are NOT accessed!
}
and in the main program we have:
int main()
{
classroom students[10];
readers(students[0]);
//and so on...
A function which is a 'friend of a Class' that is allowed to have 'read access' to its 'private members' but NOT 'write access'?
Once you declare a function as friend function, the access specifier rules are off, but you can prevent writing to members by passing in a const object to the friend function.
friend void readers(const classroom&);
^^^^^
Note that access specifiers and constness are two different attributes, do not mix them.
Note that your friend function can still try to modify the object by casting away the constness of the object by using const_cast but that would result in Undefined Behavior as per the Standard.
You'll want to read up on "const-ness", including constant variables, parameters, and member functions.
Specifically, you can specify that the friend function receive it's parameter as a const reference. The it will only be able to read private variables and call const functions.
// ...
friend void readers(classroom const &);
// ...
void readers(classroom const &lee) {
// ...
}