Can private variable of one instance be available in the function of other instance.
The following code is printing 5
#include <iostream>
class A
{
public:
A(int value) {
x = value;
}
void printValue(A *obj) {
std::cout << obj->x;
}
private:
int x;
};
void main()
{
A obj1(3);
A obj2(5);
obj1.printValue(&obj2);
getchar();
return;
}
Can anyone please explain why this happens. Thank you.
Yes, it can. private: and protected: restrictions are per class, not per instance. What matters is where the code doing the access is located. If the code accessing something private is located in the same class, or in a friend class, or a friend function, then access is allowed.
Scope of being private applies to anything inside that type, not any only this instance.
From MSDN: "When preceding a list of class members, the private keyword specifies that those members are accessible only from member functions and friends of the class."
Let's modify printValue:
void printValue()
{
A *obj = this;
std::cout << obj->x;
}
If you say this shouldn't get compiled because by obj we are trying to access element of other object. If that holds true, no class can even be made to access element of its own. Copy/Move constructors, (move) assignment operators won't work.
Yes both Obj1 and Obj2 are of class A. So the member function certainly can access anything inside the object. To get more understanding, you should try to understand how a member function actually operates on an object through which it is called.
Let us take your example and adding one more function printValue() to it to explain more:
#include <iostream>
class A
{
public:
A(int value) {
x = value;
}
void printValue(A *obj) {
std::cout << obj->x;
}
void printValue() { // who supplies 'this' pointer accessible inside the function
std::cout<< this->x;
}
private:
int x;
};
void main()
{
A obj1(3);
A obj2(5);
obj1.printValue(&obj2);
getchar();
return;
}
note that I have added a member function void printValue(); and it uses this->x, which is provided by the compiler and the function call for
obj1.printValue(&obj2) is translated by compiler to printvalue(this, &obj2).
That is why when you call obj1.printValue() that i have added, it will be called like
printValue(this) where this = &obj1 provided by the compiler.
so effectively a member function always access an object using its pointer. In your case, there are 2 objects: 1 that you provide and one that is supplied by the compiler.
I hope this explains your doubt.
This behavior is not only logical, but also very useful. Consider
class Point2D {
public:
Point2D (int x, int y) : x(x), y(y);
Point2D& operator+=(const Point2D& other) {
x += other.x;
y += other.y;
return *this;
}
private:
int x, y;
}
If you could not access other's private members in operator+=, you'd be forced to make public getters and setters and the whole point of having x and y private would be arguably lost. Hence private hides the members form the outside world, but not from instances of the same class.
Related
I am trying to learn about inheritance, and how private, protected, and public variables work.
My understanding is that a class's private variables can only be read by members of that class, and that protected variables can be read by members of that class, and by derived classes.
I am implementing some code to make sure that I understand this correctly, and I seem to be able to access variables that I didn't expect to be able to.
I have a class Polygon, and a derived class Triangle. I wrote a set of read() functions in the public areas of those classes to read their variables. These functions are overloaded so that with no arguments, read() will return the variables of the calling object, or alternatively, read(&Poly) can take another polygon as an argument and return the other polygon's variables.
#include <iostream>
using namespace std;
class Polygon;
class Triangle;
class Polygon {
private:
int privatePoly = 1;
protected:
int protectedPoly = 10;
public:
int publicPoly = 100;
// Setters
void setPrivate (int x) { privatePoly = x; }
void setProtected (int x) { protectedPoly = x; }
// Read
int readPrivate (const Polygon& inPoly) { return inPoly.privatePoly; }
int readProtected (const Polygon& inPoly) { return inPoly.protectedPoly; }
int readPublic (const Polygon& inPoly) { return inPoly.publicPoly; }
};
class Triangle : public Polygon {
private:
int privateTriangle = 3;
protected:
int protectedTriangle = privateTriangle*10;
public:
int publicTriangle = privateTriangle*100;
// Read Triangle variables
int readPrivate_Tri () { return privateTriangle; }
int readProtected_Tri () { return protectedTriangle; }
int readPublic_Tri () { return publicTriangle; }
int readPrivate_Tri (const Triangle& inTri) { return inTri.privateTriangle; }
int readProtected_Tri (const Triangle& inTri) { return inTri.protectedTriangle; }
int readPublic_Tri (const Triangle& inTri) { return inTri.publicTriangle; }
};
I instantiated one object of each type, Polygon P1, and Triangle T1, and tried to read P1's private variables from the derived class T1, expecting this to fail since private variables shouldn't be readable by derived classes. It didn't.
int main(int argc, const char * argv[]) {
Polygon P1;
Triangle T1;
// To make sure T1's polygon variables are different from P1's.
T1.setPrivate(2);
T1.setProtected(20);
// T1 reading P1
cout << "T1.readPrivate(P1): " << T1.readPrivate(P1) << endl;
cout << "T1.readProtected(P1): " << T1.readProtected(P1) << endl;
cout << "T1.readPublic(P1): " << T1.readPublic(P1) << endl << endl;
return 0;
}
This produces
T1.readPrivate(P1): 1
T1.readProtected(P1): 10
T1.readPublic(P1): 100
I thought perhaps this was related to the fact that the read functions were originally declared in the parent Polygon class (and that the private/protected specifiers referred to where the functions were declared rather than who the calling object was), so I gave the Triangle class its own copy of the readPolygon(&Polygon) variables. The following was added to the definition of the Triangle class:
// Read Polygon variables with separate function unique to Triangle class
int readProtected_P_from_T (const Polygon& inPoly) { return inPoly.protectedPoly; }
int readPublic_P_from_T (const Polygon& inPoly) { return inPoly.publicPoly; }
Where the readPublic_P_from_T() function was added to check the function format.
This doesn't compile, with the error:
"'protectedPoly' is a protected member of 'Polygon'"
I expected this to work because I thought a derived class could see protected variables.
And I expected the first readPrivate function to not work, when called from the derived class.
Could someone please explain how these access specifiers work?
Any function within a class can access its private variables. It can access protected and public variables from iherited classes as well.
If the function itself is public, anyone can call it.
Usually private variables are used for internal needs of the class by its member functions and are not intended for the public. However, public member functions can use them for doing a particular action.
In your case all member functions are public. Therefore, you can call them to access any internal data inside the class.
If you want to fail, try to access the member data directly without the function. For example
class A {
int a = 0;
public:
int b = 1;
int getA() {
return a;
}
};
A c1;
cout << c1.a << c1.b;
the compiler will fail on the member access, because a is private.
On the other hand, if you use the getA() function, it will work, because the function itself can access private members:
cout << c1.getA() << c1.b;
My understanding is that a class's private variables can only be read by members of that class, and that protected variables can be read by members of that class, and by derived classes.
That understanding is correct.
I instantiate one object of each type, Polygon P1, and Triangle T1, and tried to read P1's private variables from the derived class T1, expecting this to fail since private variables shouldn't be readable by derived classes. It didn't.
readPrivate() is a member of Polygon, so it has no problem reading Polygon's internals.
(Public) Inheritance allows Triangle to have these functions too, but since they are actually at the Polygon level, it doesn't have a problem.
This doesn't compile, with the error: "'protectedPoly' is a protected member of 'Polygon'"
You are running into this situation. That link explains that problem and its answer far better than I could, so I'll leave it right there.
Could someone please explain how these access specifiers work?
You seem to have a pretty good grasp on the subject already, except with a few minor discrepancies. However, if you wish to read up more on inheritance, here is a useful resource on it.
This is a question to find out the better programming practice:
In C++, say I have two classes one of which is a member class of the other, e.g.,
class SomeClass {
public:
MemberClass member_class;
void set_num(double num_) { num_ = num; }
double num() {return num_; }
private:
double num_;
}
I want the member class to have access to the member functions of the outer class, e.g.,
class MemberClass {
public:
PrintSquare() {
cout << num() * num() << endl;
}
}
I am trying to achieve this in order to reduce the number of function arguments I am passing all around the program.
The most common (and IMHO proper) way to solve this problem is, introducing an interface (or even more interfaces focusing on particular sets of method features) for the containing class, and pass that one to the 'inner' class member on construction:
struct Interface {
virtual void set_num(double num_) = 0;
virtual double num() const = 0;
virtual ~Interface() {}
};
class MemberClass {
public:
MemberClass(Interface& interface) : interface_(interface) {}
PrintSquare() {
cout << interface_.num() * interface_.num() << endl;
}
private:
Interface& interface_;
};
class SomeClass : public Interface {
public:
MemberClass member_class;
SomeClass() : member_class(*this), num_() {}
virtual void set_num(double num_) { num_ = num; }
virtual double num() const { return num_; }
virtual SomeClass() {}
private:
double num_;
};
NOTE:
Calling methods of the interface though will fail (with a runtime exception), when called from the MemberClass constructor definition.
Although the answer by Kerrek is very interesting, he himself already states this normally isn't the way to go. Common practice would be to make the inner class nested in the outer one, if possible. If the inner one needs access to the outer one in such a way that a nested connection seems natural, this would be the way to go. Construction of an Inner object would then need a reference to the object it is a member from, in order to be able to call functions on its parent:
class Outer
{
class Inner
{
Outer &parent; // consider constness
public:
Inner(Outer &_parent); //initializes the parent-reference
void innerFunction(); // can call members of parent
};
Inner inner;
public:
Outer(): inner(*this) { ... } // initialize inner
};
Depending on the standard you're using, the innerFunction now has access to all public members of Outer (C++03), or even all private members as well (C++11). See also this topic:
C++ nested classes - inner/outer relationship
EDIT: Did a quick test, and my compiler (gcc 4.7.2) also allows access to private members with older standards. Maybe someone could comment on this...
If your classes are all standard-layout, then you can take advantage of some layout guarantees that C++ makes, namely that a on object of standard layout type may be treated as if it were its own first member. For instance:
struct Foo
{
int a;
void barely_legal();
};
struct Bar
{
Foo x;
int y;
};
#include <type_traits>
void Foo::barely_legal()
{
static_assert(std::is_standard_layout<Foo>::value, "Foo");
static_assert(std::is_standard_layout<Bar>::value, "Bar");
Bar * p = reinterpret_cast<Bar *>(this);
++p->y;
}
This is unusual at best and cruel at worst, so please don't write code like this unless you have a really good reason to do so. (I know people who do have reason to do this, but I don't turn my back towards them.)
Hi I am pretty new to C++ and im converting C code to C++. I started by converting all the structs to classes, and added accessors and mutators for the internals, but some structs have other structs inside them. I want to know the best method for setting the internals of a class within a class, such as
struct1.struct2.struct3.i = 5;
where i is an int. Should I be passing as reference using accessors? but seeing as accessors tend to be const would this be something I should do?
something like
class1.get_class2().get_class3().set_i(5) or something if it can be done in this kind of format.
This is probably a dumb question but i have no idea how to do it, Thank You
class1.get_class2().get_class3().set_i(5)
is possible if get_class2() is non-const and returns a non-const pointer reference.
However, this approach completely breaks the encapsulation. The users of class1 should not (and must not) know that class1 uses class2 inside and that in turn uses class3 inside.
If a setter-API is absolutely necessary, then a better approach is do it hierarchically. For example
// User
class1.set_i( 5 );
// class1
class1::set_i( int x ) { class2_obj.set_i( x ); }
// class2
class2::set_i( int x ) { class3_obj.set_i( x ); }
// class3
class3::set_i( int x ) { i_ = x; }
I am not so sure about that ... did you put a class inside a class or an object inside a class ?
something like :
class OBJ1
{
//methods , and other stuff
}
class OBJ2
{
public OBJ1 *O ;
}
is valid , so you can acces a method like :
OBJ2 *N2 ;
N2->O->some_method();
however , something like
class OBJ2
{
class OBJ1;
}
is not valid :P
again... not sure if this is exactly what you asked ...
If you really have a good reason to access your member object via getters and setters, you can do the following:
class A {
public:
void f() const {}
};
class B {
public:
const A &get_a() const {
// the returned reference will be read-only, i.e. only non-const member
// functions can be called, and public members can not be written.
// it needs to be stored in a const A & object.
return a;
}
A &get_writable_a() {
return a;
}
void set_a(A &a) {
//make sure that the assignment operator of A will take care of all the
//dirty internals, such as internal buffers that need to be deleted.
this->a = a;
}
private:
//the member
A a;
};
int main() {
B b;
b.get_a().f();
}
If you don't have a good reason to do so, I'd recommend to simply make it a public member, and access it directy:
class A {
public:
void f() const {}
};
class B {
public:
A a;
};
int main() {
B b;
b.a.f();
}
Isn't that simply much more elegant?
Note that you can use friend to specify other functions or classes that are allowed to directly access your private members.
As was also pointed out in an other answer, in most cases it is a bad idea to make a member object visible to the outside at all.
This question already has answers here:
Can I access private members from outside the class without using friends?
(27 answers)
Closed 6 years ago.
I have a class A as mentioned below:-
class A{
int iData;
};
I neither want to create member function nor inherit the above class A nor change the specifier of iData.
My doubts:-
How to access iData of an object say obj1 which is an instance of class A?
How to change or manipulate the iData of an object obj1?
Note: Don't use friend.
Here's a way, not recommended though
class Weak {
private:
string name;
public:
void setName(const string& name) {
this->name = name;
}
string getName()const {
return this->name;
}
};
struct Hacker {
string name;
};
int main(int argc, char** argv) {
Weak w;
w.setName("Jon");
cout << w.getName() << endl;
Hacker *hackit = reinterpret_cast<Hacker *>(&w);
hackit->name = "Jack";
cout << w.getName() << endl;
}
Bad idea, don't do it ever - but here it is how it can be done:
int main()
{
A aObj;
int* ptr;
ptr = (int*)&aObj;
// MODIFY!
*ptr = 100;
}
You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.
(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)
EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:
NO you can't, atleast not in a portable way approved by the C++ standard.
The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.
If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
};
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
}
A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.
Modified Code Sample:
class MyClass
{
private:
int c;
public:
void doSomething()
{
c = 10; //Allowed
}
friend void MytrustedFriend();
};
void MytrustedFriend()
{
MyClass obj;
obj.c = 10; //Allowed
}
int main()
{
MyClass obj;
obj.c = 30; //Not Allowed, gives compiler error
obj.doSomething(); //Allowed
//Call the friend function
MytrustedFriend();
return 0;
}
http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html
this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.
I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.
I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.
In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!
class A {
int iData;
};
int main ()
{
A a;
struct ATwin { int pubData; }; // define a twin class with public members
reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value
return 0;
}
There's no legitimate way you can do it.
Start making friends of class A. e.g.
void foo ();
class A{
int iData;
friend void foo ();
};
Edit:
If you can't change class A body then A::iData is not accessible with the given conditions in your question.
iData is a private member of the class. Now, the word private have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.
It's possible to access the private data of class directly in main and other's function...
here is a small code...
class GIFT
{
int i,j,k;
public:
void Fun()
{
cout<< i<<" "<< j<<" "<< k;
}
};
int main()
{
GIFT *obj=new GIFT(); // the value of i,j,k is 0
int *ptr=(int *)obj;
*ptr=10;
cout<<*ptr; // you also print value of I
ptr++;
*ptr=15;
cout<<*ptr; // you also print value of J
ptr++;
*ptr=20;
cout<<*ptr; // you also print value of K
obj->Fun();
}
friend is your friend.
class A{
friend void foo(A arg);
int iData;
};
void foo(A arg){
// can access a.iData here
}
If you're doing this regularly you should probably reconsider your design though.
access private members outside class ....only for study purpose ....
This program accepts all the below conditions
"I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."
//here member function is used only to input and output the private values ...
//void hack() is defined outside the class...
//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>
class A
{
private :int iData,x;
public: void get() //enter the values
{cout<<"Enter iData : ";
cin>>iData;cout<<"Enter x : ";cin>>x;}
void put() //displaying values
{cout<<endl<<"sum = "<<iData+x;}
};
void hack(); //hacking function
void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}
void hack() //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck; //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}
I understand the meaning of 'this', but I can't see the use case of it.
For the following example, I should teach the compiler if the parameter is the same as member variable, and I need this pointer.
#include <iostream>
using namespace std;
class AAA {
int x;
public:
int hello(int x) { this->x = x;}
int hello2(int y) {x = y;} // same as this->x = y
int getx() {return x;}
};
int main()
{
AAA a;
a.hello(10); // x <- 10
cout << a.getx();
a.hello2(20); // x <- 20
cout << a.getx();
}
What would be the use case for 'this' pointer other than this (contrived) example?
Added
Thanks for all the answers. Even though I make orangeoctopus' answer as accepted one, it's just because he got the most vote. I must say that all the answers are pretty useful, and give me better understanding.
Sometimes you want to return yourself from an operator, such as operator=
MyClass& operator=(const MyClass &rhs) {
// assign rhs into myself
return *this;
}
The 'this' pointer is useful if a method of the class needs to pass the instance (this) to another function.
It's useful if you need to pass a pointer to the current object to another function, or return it. The latter is used to allow stringing functions together:
Obj* Obj::addProperty(std::string str) {
// do stuff
return this;
}
obj->addProperty("foo")->addProperty("bar")->addProperty("baz");
In C++ it is not used very often. However, a very common use is for example in Qt, where you create a widget which has the current object as parent. For example, a window creates a button as its child:
QButton *button = new QButton(this);
When passing a reference to an object within one of its methods. For instance:
struct Event
{
EventProducer* source;
};
class SomeContrivedClass : public EventProducer
{
public:
void CreateEvent()
{
Event event;
event.source = this;
EventManager.ProcessEvent(event);
}
};
Besides obtaining a pointer to your own object to pass (or return) to other functions, and resolving that an identifier is a member even if it is hidden by a local variable, there is an really contrived usage to this in template programming. That use is converting a non-dependent name into a dependent name. Templates are verified in two passes, first before actual type substitution and then again after the type substitution.
If you declare a template class that derives from one of its type parameters you need to qualify access to the base class members so that the compiler bypasses the verification in the first pass and leaves the check for the second pass:
template <typename T>
struct test : T {
void f() {
// print(); // 1st pass Error, print is undefined
this->print(); // 1st pass Ok, print is dependent on T
}
};
struct printer {
void print() { std::cout << "print"; }
};
struct painter {
void paint() { std::cout << "paint"; }
};
int main() {
test<printer> t; // Instantiation, 2nd pass verifies that test<printer>::print is callable
t.f();
//test<painter> ouch; // 2nd pass error, test<painter>::print does not exist
}
The important bit is that since test inherits from T all references to this are dependent on the template argument T and as such the compiler assumes that it is correct and leaves the actual verification to the second stage. There are other solutions, like actually qualifying with the type that implements the method, as in:
template <typename T>
struct test2 : T {
void f() {
T::print(); // 1st pass Ok, print is dependent on T
}
};
But this can have the unwanted side effect that the compiler will statically dispatch the call to printer::print regardless of whether printer is a virtual method or not. So with printer::print being declared virtual, if a class derives from test<print> and implements print then that final overrider will be called, while if the same class derived from test2<print> the code would call printer::print.
// assumes printer::print is virtual
struct most_derived1 : test<printer> {
void print() { std::cout << "most derived"; }
};
struct most_derived2 : test2<printer> {
void print() { std::cout << "most derived"; }
};
int main() {
most_derived1 d1;
d1.f(); // "most derived"
most_derived2 d2;
d2.f(); // "print"
}
You can delete a dynamically created object by calling delete this from one of its member functions.
The this pointer is the pointer to the object itself. Consider for example the following method:
class AAA {
int x;
public:
int hello(int x) { some_method(this, x);}
};
void somefunc(AAA* a_p)
{
......
}
class AAA {
int x;
public:
int hello(int x) { this->x = x;}
int hello2(int y) {x = y;} // same as this.x = y
int getx() {return x;}
void DoSomething() { somefunc(this); }
};
this is implicit whenever you use a member function or variable without specifying it. Other than that, there are many, many situations in which you'll want to pass the current object to another function, or as a return value.
So, yeah, it's quite useful.
Sometimes you need to refer to "this" object itself, and sometimes you may need to disambiguate in cases where a local variable or a function parameter shadows a class member:
class Foo {
int i;
Foo* f() {
return this; // return the 'this' pointer
}
void g(){
j(this); // pass the 'this' pointer to some function j
}
void h(int i) {
this->i = i; // need to distinguish between class member 'i' and function parameter 'i'
}
};
The two first cases (f() and g() are the most meaningful cases. The third one could be avoided just by renaming the class member variable, but there's no way around using this in the first two cases.
Another possible use case of this:
#include <iostream>
using namespace std;
class A
{
public:
void foo()
{
cout << "foo() of A\n";
}
};
class B : A
{
public:
void foo()
{
((A *)this)->foo(); // Same as A::foo();
cout << "foo() of B\n";
}
};
int main()
{
B b;
b.foo();
return 0;
}
g++ this.cpp -o this
./this
foo() of A
foo() of B
One more use of this is to prevent crashes if a method is called on a method is called on a NULL pointer (similar to the NULL object pattern):
class Foo
{
public:
void Fn()
{
if (!this)
return;
...
}
};
...
void UseFoo(Foo* something)
{
something->Fn(); // will not crash if Foo == NULL
}
If this is useful or not depends on the context, but I've seen it occasionally and used it myself, too.
self-assignment protection