Access Specifier Does Not Change Accessibility Level. What does this mean? - c++

I am just wondering what this message means on visual studio. Does this mean that by default variables inside classes are set to private. I cannot get a clear answer to this question anywhere.
This is my code:
#pragma once
class number
{
private: // <-- that is grey in the IDE and it shows the text box when you hover over it
int random_number;
public:
number(int x);
int get_number() const { return random_number; }
void set_number(int number) { random_number = number; }
~number();
};

If you don't specify anything, private is implicit when you define a class by means of the class keyword. In other terms, the following definitions are identical:
class C {
int i;
};
class C {
private:
int i;
};
The opposite is true if you use the keyword struct instead of class:
struct C {
int i;
};
struct C {
public:
int i;
};
That is, Visual Studio is telling you that the private is superfluous. Your data member is a private one in both cases.

You probably accidentally wrote public or private two times consecutively. And the second access specifier does nothing.
Variables inside classes are set to private by default and variables inside structs are set to public, so this can be the cause of the message too.

Related

Library of implicitly friend classes

I am developing a C++ class library. The classes have "public" methods aimed at users, and "protected" ones supplying extra services reserved for internal use.
The classes do not derive from each other. In my current model, they need to be explicitly declared friends of each other. Is there a more compact/convenient way to achieve the same effect ?
Example:
class A
{
public:
static int ExposedA() { return 1; }
static int ExposedB();
static int ExposedC();
private:
static int Internal() { return 0; }
friend class B;
friend class C;
};
class B
{
public:
static int ExposedA() { return 2 + A::Internal(); }
static int ExposedB() { return 2; }
static int ExposedC();
private:
static int Internal() { return 0; }
friend class A;
friend class C;
};
class C
{
public:
static int ExposedA() { return 3 + A::Internal(); }
static int ExposedB() { return 3 + B::Internal(); }
static int ExposedC() { return 3; }
private:
static int Internal() { return 0; }
friend class A;
friend class B;
};
int A::ExposedB() { return 1 + B::Internal(); }
int A::ExposedC() { return 1 + C::Internal(); }
int B::ExposedC() { return 2 + C::Internal(); }
In practice, maintenance of the friends list is tedious, and forward references force to move the definitions out of the classes.
I reckon the short answer is "no".
In the comments (for anyone reading this in the future), you identified your problem as "a case of intentional strong coupling" as stated in an answer to this question (emphasis mine):
In general, friend classes are useful in designs where there is intentional strong coupling: you need to have a special relationship between two classes. More specifically, one class needs access to another classes's internals and you don't want to grant access to everyone by using the public access specifier.
The answer goes on to state:
The rule of thumb: If public is too weak and private is too strong, you need some form of selected access: either protected or friend (the package access specifier in Java serves the same kind of role).
In other words, if public doesn't work for you, and private doesn't work for you, you are left protected and friend. If you also can't use protected, then you are stuck with friend by the process of elimination. You can't change the language (unless you want to submit a paper to the committee, but that's a whole other topic entirely). You are left to juggle the these access specifiers around the best way you can.
To the question of which way is the best way to use these specifiers, I have no answer. It's nearly impossible for me to know what juggle combination will work best for your situation. So far, your solution seems to be the best. Nothing off the top of my head seems better, given your constraints.
it is internal to the class library. Users should have no access, libraries in the class should have mutual access.
If I'm understanding you correctly (and I may not be), I will say that you do have the (untested) option of having dual headers: one for you, and one for the end user. In your header, you can make the function public like this:
// YouB.h
class B
{
public:
static int ExposedA() { return 2 + A::Internal(); }
static int ExposedB() { return 2; }
static int ExposedC();
// This is a public function. Your compiler should have no problem with other classes using it
static int Internal() { return 0; }
};
Then, you have a different header for your users:
// UserB.h
// YouB.h
class B
{
public:
static int ExposedA() { return 2 + A::Internal(); }
static int ExposedB() { return 2; }
static int ExposedC();
private:
// This is a now a private or protected function.
// I haven't tested this, so I don't know if the other access thing will work,
// but since it's solely an internal function, commenting it out or removing
// it completely should work too
static int Internal() { return 0; }
};

Multiple public/private keyword in class definition

I have seen multiple public and private keywords in a class definition, like the example below:
class myClass
{
public:
void func1(){}
public:
void func2(){}
private:
int x;
int y;
private:
int z;
int baz;
};
What is the practical use of this (if any)? Is there any situation in which this could be useful?
Is there any situation in which this could be useful?
I can think of a situation where it would be very problematic otherwise:
class myClass
{
public:
void func1(){}
public:
void func2(){}
COORDINATES; // <-- Note the macro here!
private:
int z;
int baz;
};
which, after the expansion of the COORDINATES macro, becomes:
class myClass
{
public:
void func1(){}
public:
void func2(){}
private:
int x;
int y;
private:
int z;
int baz;
};
If multiple private / public keywords weren't allowed, it would be very painful to do it. Although using macros isn't good practice; neither is introducing access modifiers silently for all the members appearing after the macro. Nevertheless, it could be useful for RAD tools generating C++ source code.
I can only guess why you see that in human written classes. My guess is that it is poor coding; the writer probably wanted to express that a chunk of data belongs together and / or wanted to be able to move up and down those chunks within the class definition, together with the corresponding access modifier (private/protected/public).
I'll go one step farther from my comment for this answer, with a snippet of code.
class myClass {
// initializers etc
public:
myClass();
~myClass();
// signal processing
public:
void modifyClass();
private:
float signalValue;
// other class responsibilities
public:
void doWork();
private:
void workHelper();
};
and so on. I wouldn't say this is a solid DESIGN for the class, but it's a good way to show the different capabilities of a class.
Another use is when you want to have a specific destruction order. Lets consider two cases:
Bad case
// Auxiliary class
Class StorageCleaner {
public:
StorageCleaner(ExternalStorage* storage) : storage_(storage);
~StorageCleaner() { storage_->DeleteEverything(); }
private:
ExternalStorage* const storage_; // Not owned
}
// Class with bad declaration order
Class ExternalStorageWrapper {
public:
ExternalStorageWrapper(ExternalStorage* storage) : cleaner_(storage) {
pointer_to_storage_.reset(storage);
}
const StorageCleaner cleaner_;
private:
std::unique_ptr<ExternalStorage> pointer_to_storage_;
// Other data which should be private
int other_int;
string other_string;
....
};
What happens when existing ExternalStorageWrapper object goes out of scope?
The ExternalStorageWrapper destructor will first
destroy other data
Then it will destroy external storage pointed by pointer_to_external_storage_ (because fields are destroyed in reversed declaration order).
Then it will attempt to destroy cleaner_
But cleaner inside its own destructor attempts to manipulate external storage, which has already been destroyed!
Good case
// Class StorageCleaner same as before
...
// Class with better declaration order
Class ExternalStorageWrapper {
private:
std::unique_ptr<ExternalStorage> pointer_to_storage_;
public:
ExternalStorageWrapper(ExternalStorage* storage) : cleaner_(storage) {
pointer_to_storage_.reset(storage);
}
const StorageCleaner cleaner_;
private:
// Other data which should be private
int other_int;
string other_string;
....
};
What happens in this case when existing ExternalStorageWrapper object goes out of scope?
The ExternalStorageWrapper destructor will first destroy other data.
Then it will attempt to destroy cleaner_. Cleaner will DeleteEverything() from storage using storage_ pointer to still existing storage.
Finally, storage gets destroyed through pointer_to_storage_.
I actually had to debug such problem in a company, so although rare, this peculiar case is possible to occur.
One use case I encounter is for the clarity. As shown in the example below, class1 inherits base class which contains a pure virtual function that class1 needs to implement. To indicate that method1 in class1 is coming from some other class class1 inherits from (e.g. base) instead of class1's own function, we use another public to make this point clear:
class base {
public:
virtual void method1() = 0;
}
class class1: base {
public:
myOwnMethod1();
myOwnMethod2();
public: /* base interface */
method1();
Just finished reading those examples. Hopefully this one could contribute on how useful multiple keyword definition is.
We don't quite need to assume much since this is my current problem as of now but consume the following:
class IOHandler {
public:
enum COLOR_DEFINITIONS : unsigned char
{
BLACK,
DARK_ER_BLUE,
DARK_GREEN,
DARK_SKY_BLUE,
DARK_RED,
DARK_PINK,
DARK_YELLOW,
DARK_WHITE,
DARK_GREY,
DARK_BLUE,
BRIGHT_GREEN,
BRIGHT_SKY_BLUE,
BRIGHT_RED,
BRIGHT_PINK,
BRIGHT_YELLOW,
BRIGHT_WHITE
};
template <typename dtEX>
void showOutputEx(dtEX literalOutput, _COLOR_OUTPUT textColorSet = {COLOR_DEFINITIONS::BRIGHT_WHITE , COLOR_DEFINITIONS::BRIGHT_YELLOW}, bool appendOutputType = true, OUTPUT_TYPE levelOutput = OUTPUT_TYPE::OUTPUT_NORMAL, EMBRACE_TYPE embraceOutputType = EMBRACE_TYPE::EMBRACE_OUTPUT_LEVEL, ...);
// ! ^^^^^^^^^^^^^^ Doesn't detect the struct being referenced at which is at below.
private:
typedef struct colorProps // This is the struct that the public function where trying to get referenced at but failed to do so.
{
unsigned char C_BG = 0,
C_FG = 0;
} _COLOR_OUTPUT;
};
The error code.
identifier "_COLOR_OUTPUT" is undefined.
At this point, my intelliSense keep complaining that _COLOR_OUTPUT is undefined within public class scope.
The most probable solution is to put the struct inside public scope instead of private scope.
But I don't want to.
The reason this happens was due to the compiler reads the file from top to bottom. Anything that is declared
that requires reference should be on top and that should resolve the issue. Since I don't want to make things messed up by putting all private class functions and variables
on top. I should just declare another specifier on the top so that any public function requiring some reference might see it ahead.
So the solution is the following: (Is to move all referrable variables and struct on top of the class so that any private and public function argument reference is being recognized.)
class IOHandler {
// Private Class Scope for Variables and Structure
private:
typedef struct colorProps // This is the struct we move at the top for recognizing references.
{
unsigned char C_BG = 0,
C_FG = 0;
} _COLOR_OUTPUT;
public:
enum COLOR_DEFINITIONS : unsigned char
{
BLACK,
DARK_ER_BLUE,
DARK_GREEN,
DARK_SKY_BLUE,
DARK_RED,
DARK_PINK,
DARK_YELLOW,
DARK_WHITE,
DARK_GREY,
DARK_BLUE,
BRIGHT_GREEN,
BRIGHT_SKY_BLUE,
BRIGHT_RED,
BRIGHT_PINK,
BRIGHT_YELLOW,
BRIGHT_WHITE
};
template <typename dtEX>
void showOutputEx(dtEX literalOutput, _COLOR_OUTPUT textColorSet = {COLOR_DEFINITIONS::BRIGHT_WHITE , COLOR_DEFINITIONS::BRIGHT_YELLOW}, bool appendOutputType = true, OUTPUT_TYPE levelOutput = OUTPUT_TYPE::OUTPUT_NORMAL, EMBRACE_TYPE embraceOutputType = EMBRACE_TYPE::EMBRACE_OUTPUT_LEVEL, ...);
// ! ^^^^^^^^^^^^^^ Now recognizable reference.
private:
... // Any other functions, excerpt.
};

why getting errors in c++ program?

I think I have coded everything correctly in this program but still getting errors.
The object si it says it's not accessible.
#include<conio.h>
#include<iostream.h>
class s_interest
{
int p,t;
float r;
s_interest(int a, int b, float c)
{
p=a;
r=b;
t=c;
}
void method()
{
int result=(float)(p*t*r)/100;
cout<<"Simple interest:"<<result;
}
};
void main()
{
int pr,ti;
float ra;
cout<<"\n Enter the principle, rate of interest and time to calculate Simple Interest:";
cin>>pr>>ti>>ra;
s_interest si(pr,ti,ra);
si.method();
}
When the compiler tells you that something is not accessible, it's talking about the public: vs. protected: vs. private: access control. By default, all members of a class are private:, so you cannot access any of them from main(), including the constructor and the method.
To make the constructor public, add a public: section to your class, and put the constructor and the method there:
class s_interest
{
int p,t;
float r;
public: // <<== Add this
s_interest(int a, int b, float c)
{
...
}
void method()
{
...
}
};
Default member access for a class is private (whereas the default for struct is public). You need to make the constructor and method() public:
class s_interest
{
int p,t; // private
float r; // also private
public: // everything that follows has public access
s_interest(int a, int b, float c) { .... }
void method() { ....}
};
Note also that void main() is not standard C++. The return type needs to be int, so you need
int main()
{
...
}
And finally, iostream.h is not a standard C++ header. You need to include <iostream> if you are using a standards compliant C++ implementation.
Following High Integrity C++ Coding Standard guidelines, always declare first public, then protected and private members. See Rule 3.1.1 of hicpp-manual-version-3-3.pdf
All the variables & functions in your class are private. This is the default when access is not specified with the private: , protected: and public: specifiers. I suggest you have a good read of a tutorial - google C++ classes.
also it is int main() and never void main()
The problem is due to access specifiers. By default class methods and data members are private. Make your data members private and methods public. so you can set the private data members value using public methods.
class{
private:
int a;
int b;
int c;
public:
void method();
void print_sum();
};

How access class variables in c++

Is it possible in c++ to access class variables in other classes without creating an object. I have tried to use static, but the other class doesnt recognize my variable.
I have 3 classes. In two of those the sae variables should be used. In the third class I am changing the values. Would be grateful if you could help. Maybe youve got an example.
class Myclass
{
public:
static int i;
};
int Myclass::i = 10;
class YourClass
{
public:
void doSomething()
{
Myclass::i = 10; //This is how you access static member variables
}
};
int main()
{
YourClass obj;
obj.doSomething();
return 0;
}
static is the right keyword here:
class A {
public:
static int i; // <-- this is a class variable
};
class B {
public:
void f() { A::i = 3; } // <-- this is how you access class variables
};
They only potential problem I can think of is that
You made the class variable protected or private, thus rendering it inaccessible from other code.
You forgot to specify the full scope of the class variable (with A:: in this example).
I think the Singleton Pattern would help, but I'm no big fan of it. A lot better design would be to have one class take ownership of the object, and pass references to this object to the other classes.
yes you can bro, try this
struct car{
string model;
string paint;
int price;
};
int main(){
// creates an object of the class car
car BMW;
// assign the values
bmw.model = "m sports";
bmw.paint ="red";
bmw.price = 24000;
}

How to access private data members outside the class without making "friend"s? [duplicate]

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