Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Are private non static variable/methods accessible in static function? If yes,
then what is the use of "Private" access modifier?. Please go through the below code.
// Testclassheader.h file
class TestClass{
private:
int TestVariable; //Private Variable
int TestFunction(); //Private Method
public:
static void TeststaticFn(); //Static Method
};
void TestClass::TeststaticFn()
{
TestClass TestObj;
TestObj.TestVariable = 10; // Compiles perfectly
TestObj.TestFunction(); //Compiles Perfectly
}
// Another Class
//#include "Testclassheader.h"
class AnotherClass{
public:
int DummyFunc();
};
int AnotherClass::DummyFunc()
{
TestClass AnotherObj;
AnotherObj.TestVariable = 15; //error: 'TestVariable' is a private member of 'TestClass'
AnotherObj.TestFunction(); //error: 'TestFunction' is a private member of 'TestClass'
}
I tried the above code in Visual studio 12. Can anyone explain why private variable/methods are accessible in static method( which actually it should not)?
All functions of a given class have access to of that class's private members through any instance. You seem to think that private limit access to member functions of that particular instance, which is incorrect.
class foo
{
private:
int bar;
// access of the function doesn't matter, but let's use public
public:
// the only case you thought was legal:
void baz()
{
bar = 1;
}
// but this is perfectly legal
void qux(foo otherFoo)
{
otherFoo.bar = 1;
}
// also legal, as you discovered.
static void quux(foo iPittyTheFoo)
{
iPittyTheFoo.bar = 1;
}
};
class someOtherClass
{
// no function here (static or otherwise) has access to baz.
// UNLESS you "friend someOtherClass" inside class foo. Whether or not
// "friend" is ever a good idea is a matter of some debate.
};
void someGlobalFunction()
{
// Also cannot access bar.
Foo a;
a.bar = 1; // boom
}
// nope. Still cannot access bar.
foo b;
someOtherClass instance(b.bar); // boom
Also, "// throws error" is misleading. "Throw" exclusively refers to exception handling, not compile time errors. Compiler errors, linker errors, and runtime errors are each quite different and require different kinds of problem solving to deal with. When asking for help from someone not looking at the actual error output, you need to specify which it is. Just copy-paste-ing the error itself is generally a good idea, then we all have the same information.
In general, I suspect you've misunderstood the purpose of public:, protected:, and private:. We all had to learn it at some point.
In C++, public functions/methods and variables/members (different people use different terms) represent a class's "interface". These are what everything outside that class is allowed to use. What goes on behind that interface is none of their business (at least in theory).
protected functions and variables are available to classes that inherit from that class. "Your version of this class may be customized in these ways".
private functions and variables are no one else's concern. No touchy. As programs change, implementation details within a given class can vary wildly. The initial implementation of a class might (shudder) return a hardcoded value:
class X
{
...
private:
int Y() { return 1; }
};
Later versions of that same function might look up a value in a database, read from a file, whatever. "Which database?" Okay, now we need a parameter...
int Y(WhichDb thisOne) { return thisOne.lookupY(); }
So everywhere that was calling Y now needs to pass in a WhichDb (which should probably be a const reference, but that's a whole different topic). By changing the "function signature" of Y, we have broken all the code that called Y. In other words, all existing calls to Y are now compiler errors, because they don't pass in a WhichDb. In one sense, public/protected/private define just how much code a given change will affect/break.
Private? Just that class. No problem, I'm responsible for that class (because I can change it's header), so fixing that is no problem.
Protected? That class, plus everything that inherits from it. This could easily Break Someone Else's Code, which is generally bad. Breaking code you're not responsible for is a great way to lose customers.
Public? Anyone, anywhere could have called that function. "Breaking changes" to public interfaces are to be avoided.
So maybe your class is only ever used inside you company, in your department, by you. Public changes at that point are no big deal. On the other hand, Some Popular Library really cannot do that. I mean... they COULD, but they'd probably piss off lots of folks.
There are ways to change your public interface without breaking existing code. You can add new functions, you can add new parameters to existing functions THAT HAVE DEFAULTS: void foo(int bar = 2);. People who called foo() will still compile (and hopefully will still get the same behavior they depended on), but now people can call foo(3) to get new behavior.
Are private non static variable/methods accessible in static function?
Yes, private non static variable/methods are accessible by a static function that is part of the self-same class.
If yes, then what is the use of "Private" access modifier?
It prevents other classes from accessing the private class members and private instance members of the class.
Can anyone explain why private variable/methods are accessible in static method?
Because all the parts of a class are part of the class.
which actually [private variable/methods] should not [be accessible to static methods of the same class])?
That is incorrect.
Related
Problem
I would like to detect if a class has member variables and fail a static assert if they do. Something like:
struct b {
int a;
}
static_assert(!has_member_variables<b>, "Class should not contain members"). // Error.
struct c {
virtual void a() {}
void other() {}
}
static_assert(!has_member_variables<c>, "Class should not contain members"). // Fine.
struct d : c {
}
static_assert(!has_member_variables<d>, "Class should not contain members"). // Fine.
struct e : b {
}
static_assert(!has_member_variables<e>, "Class should not contain members"). // Error.
struct f : c {
char z;
}
static_assert(!has_member_variables<f>, "Class should not contain members"). // Error.
Is there a way to achieve this with SFINAE template? This class may have inheritance or even multiple inheritance with virtual functions (no members in the base classes though).
Motivation
I have a pretty simple setup as follows:
class iFuncRtn {
virtual Status runFunc(Data &data) = 0;
};
template <TRoutine, TSpecialDataType>
class FuncRoutineDataHelper : public iFuncRtn {
Status runFunc(Data &data) {
static_assert(!has_member_variables<TRoutine>, "Routines shouldnt have data members!");
// Prepare special data for routine
TSpecialDataType sData(data);
runFuncImpl(sData);
}
class SpecificRtn :
public FuncRoutineDataHelper<SpecificRtn, MySpecialData> {
virtual Status runFuncImpl(MySpecialData &sData) {
// Calculate based on input
sData.setValue(someCalculation);
}
};
The FunctionalityRoutines are managed and run on a per tick basis. They are customized and can perform a wide variety of tasks such as contacting other devices etc. The data that is passed in can be manipulated by the routine and is guaranteed to be passed in on each tick execution until the functionality is finished. The right type of data is passed in based on the DataHelper class. I wan't to discourage future people from mistakenly adding data to the functionality routines as it is very unlikely to do what they expect. To force this, I was hoping to find a way with static assert.
You can solve this by depending on the compiler doing empty base class optimizations, by checking if a class derived from your T has the same size as an empty class with virtual functions:
template<typename T, typename... BaseClasses>
class IsEmpty
{
// sanity check; see the updated demo below
static_assert(IsDerivedFrom<T, BaseClasses...>::value);
struct NonDerived : BaseClasses... { virtual ~NonDerived() = default; };
struct Derived : T { virtual ~Derived() = default; };
public:
inline static constexpr bool value = (sizeof(NonDerived) == sizeof(Derived));
};
This should work with both single and multiple inheritance. However, when using multiple inheritance, it's necessary to list all base classes, like that:
static_assert(IsEmpty<Derived, Base1, Base2, Base3>::value);
Obviously, this solution rules out final classes.
Here's the updated demo.
Here's the original demo. (doesn't work with multiple inheritance)
You will have to mark the classes in some way or another. Pick a way you are comfortable with, a property or some kind of type integer member with an enum. Whoever makes sub-classes will have to follow your convention to make it work.
All other answers here will be some variant of this.
Any answer that uses a sizeof could not guarantee this will work between platforms, compilers, or even classes on the same platform and compiler, due to easily being able to fit a new member inside the default class member alignment, where the sizes of sizeof could easily end up the same for a sub-class.
Background:
As stated in your code and question, all of that is just plain and basic C ad C++ code, and is resolved entirely at compile time. The compiler will tell you if a member exists or not. After its compiled it's a mash of efficient, nameless, machine code with no hints or help for that kind of thing by itself.
Any name you use for a function or data member effectively disappears, as you know it and see it there, after compile and there is no way to lookup any member by name. Each data member is known only by its numerical offset from the top of the class or struct.
Systems like .Net, Java, and others are designed for reflection, which is the ability to remember class members by name, where you can find them at runtime when you program is running.
Templates in C++, unless mixed mode C++ on something like .Net, are also all resolved at compile time, and the names will also all be gone, so the templates by themselves buy you nothing.
Languages like Objective-C also are written to not fail necessarily if certain types of special members are missing, similar to what you are asking, but under the covers its using a lot of supporting code and runtime management to keep track independently, where the actual function itself and its code are still unware and rely on other code to tell them if a member exists or to not fail on null member.
In pure C or C++ you will need to just make your own system, and be literal about tracking dynamically what does what. You could make enums, or lists or dictionaries of name strings. This is what is normally done, you just have to leave hints for yourself. A class cannot be compiled in a way that gives implicit visibility to future sub-classes by definition, without using some form if RTTI.
Its common to put a type member on a class for this very reason, which could be a simple enum. I would not count on sizes or anything that might be platform dependent.
In the 2017 cppcon videos, I came across a talk by Klaus Iglberger which was entitled "Free Your Functions!".
In this talk, the speaker talked about how switching to free functions could
easy up the process of testing private methods (See at 19:00). The idea is that you pull the
private method out of the class (you make it a free function) and it becomes testable.
At first, I found the idea interesting, but then the
more I thought about it, the less I understood how this is actually supposed to work. For example,
let's say I have the following (dummy) class:
class SomeClass
{
public:
SomeClass();
~SomeClass();
void someTask();
private:
void someComplexTask();
void someOtherComplexTask();
};
void SomeClass::someTask()
{
someComplexTask();
someOtherComplexTask();
}
// private tasks implementations...
Then someComplexTask() and someOtherComplexTask() are private methods. This means that they
are implementation details, i.e. that they can only be called inside SomeClass (or friends). It
seems to me that if you make them free functions, yes they become testable, but they are no longer
private, nor a mere implementation detail specific to SomeClass. In fact, they can be called from anywhere in the code...
So my question is: why is Mr. Iglberger's point valid?
This is a clear indication that you have a design flaw. If you have a
private function that you need to test and you have to bend backwards
to make it work then something is wrong. You have missed something.
Your design doesn't work.
His point is not to just make private functions free. He is not saying: "get all your private functions and make them free functions". He is saying that functionality that needs to be tested shouldn't be an implementation detail because if you need to test it that is an indication the functionality is useful.
Please pay close attention to the transformation he does to the code:
initial code:
class X
{
public:
void doSomething( ... ) {
...
resetValues();
...
}
...
private:
void resetValues() {
for( int& value : values_ )
value = 0;
}
std::vector<int> values_;
};
He pulls resetValues out of X but it makes it operate on a std::vector<T>, not on X:
void resetValues( std::vector<int>& vec )
{
for( int& value : vec )
value = 0;
}
Now resetValues is a functionality that can be reused and tested. As it truly has nothing to do with X, but with resetting all values of a vector it is a valid design to make it a free function instead of a private X method.
I like how Rann Lifshitz put it in his comment:
I think the better way to go here is to understand that some private
functions are, in fact, common utility functions
I have watched the video too. But, I have a few disagreements.
1- Does your method require accessing fields? If not, it does not belong to the class. But if it does, they need the fields. The free functions do not have access to the fields unless you pass them as function arguments. Please consider that free functions should not be looked as public function.
2- Not everything is supposed to be free function. But it is a good practice to avoid putting everything in the class when they are not necessary.
3- Private function are not often supposed to be tested. But if you insist, you might be able to perform such as invalid hack (which not always works as mentioned in the comments):
#define class struct
#define private public
#define protected public
#include "library.h"
#undef class
#undef private
#undef protected
Freeing your function is neater but not more feasible.
I am starting to code bigger objects, having other objects inside them.
Sometimes, I need to be able to call methods of a sub-object from outside the class of the object containing it, from the main() function for example.
So far I was using getters and setters as I learned.
This would give something like the following code:
class Object {
public:
bool Object::SetSubMode(int mode);
int Object::GetSubMode();
private:
SubObject subObject;
};
class SubObject {
public:
bool SubObject::SetMode(int mode);
int SubObject::GetMode();
private:
int m_mode(0);
};
bool Object::SetSubMode(int mode) { return subObject.SetMode(mode); }
int Object::GetSubMode() { return subObject.GetMode(); }
bool SubObject::SetMode(int mode) { m_mode = mode; return true; }
int SubObject::GetMode() { return m_mode; }
This feels very sub-optimal, forces me to write (ugly) code for every method that needs to be accessible from outside. I would like to be able to do something as simple as Object->SubObject->Method(param);
I thought of a simple solution: putting the sub-object as public in my object.
This way I should be able to simply access its methods from outside.
The problem is that when I learned object oriented programming, I was told that putting anything in public besides methods was blasphemy and I do not want to start taking bad coding habits.
Another solution I came across during my research before posting here is to add a public pointer to the sub-object perhaps?
How can I access a sub-object's methods in a neat way?
Is it allowed / a good practice to put an object inside a class as public to access its methods? How to do without that otherwise?
Thank you very much for your help on this.
The problem with both a pointer and public member object is you've just removed the information hiding. Your code is now more brittle because it all "knows" that you've implemented object Car with 4 object Wheel members. Instead of calling a Car function that hides the details like this:
Car->SetRPM(200); // hiding
You want to directly start spinning the Wheels like this:
Car.wheel_1.SetRPM(200); // not hiding! and brittle!
Car.wheel_2.SetRPM(200);
And what if you change the internals of the class? The above might now be broken and need to be changed to:
Car.wheel[0].SetRPM(200); // not hiding!
Car.wheel[1].SetRPM(200);
Also, for your Car you can say SetRPM() and the class figures out whether it is front wheel drive, rear wheel drive, or all wheel drive. If you talk to the wheel members directly that implementation detail is no longer hidden.
Sometimes you do need direct access to a class's members, but one goal in creating the class was to encapsulate and hide implementation details from the caller.
Note that you can have Set and Get operations that update more than one bit of member data in the class, but ideally those operations make sense for the Car itself and not specific member objects.
I was told that putting anything in public besides methods was blasphemy
Blanket statements like this are dangerous; There are pros and cons to each style that you must take into consideration, but an outright ban on public members is a bad idea IMO.
The main problem with having public members is that it exposes implementation details that might be better hidden. For example, let's say you are writing some library:
struct A {
struct B {
void foo() {...}
};
B b;
};
A a;
a.b.foo();
Now a few years down you decide that you want to change the behavior of A depending on the context; maybe you want to make it run differently in a test environment, maybe you want to load from a different data source, etc.. Heck, maybe you just decide the name of the member b is not descriptive enough. But because b is public, you can't change the behavior of A without breaking client code.
struct A {
struct B {
void foo() {...}
};
struct C {
void foo() {...}
};
B b;
C c;
};
A a;
a.c.foo(); // Uh oh, everywhere that uses b needs to change!
Now if you were to let A wrap the implementation:
class A {
public:
foo() {
if (TESTING) {
b.foo();
} else {
c.foo();
}
private:
struct B {
void foo() {...}
};
struct C {
void foo() {...}
};
B b;
C c;
};
A a;
a.foo(); // I don't care how foo is implemented, it just works
(This is not a perfect example, but you get the idea.)
Of course, the disadvantage here is that it requires a lot of extra boilerplate, like you have already noticed. So basically, the question is "do you expect the implementation details to change in the future, and if so, will it cost more to add boilerplate now, or to refactor every call later?" And if you are writing a library used by external users, then "refactor every call" turns into "break all client code and force them to refactor", which will make a lot of people very upset.
Of course instead of writing forwarding functions for each function in SubObject, you could just add a getter for subObject:
const SubObject& getSubObject() { return subObject; }
// ...
object.getSubObject().setMode(0);
Which suffers from some of the same problems as above, although it is a bit easier to work around because the SubObject interface is not necessarily tied to the implementation.
All that said, I think there are certainly times where public members are the correct choice. For example, simple structs whose primary purpose is to act as the input for another function, or who just get a bundle of data from point A to point B. Sometimes all that boilerplate is really overkill.
There's something I recurently struggle with while working on C++ code.
Let's say I've got a method doing X, Y and then Z. Now I'd like to introduce another method that should do X, Y', Z. If that was plain old C code, I'd then make functions X() and Z() with the common code, declaring them static so that the compiler would now they can be inlined if needed, as no code out of this "module" can call them. The method that's part of the API would then look like
int M(args) {
X(foo); // that could e.g. be "check args are valid".
/* here comes M-specific code */
Z(bar); // that could e.g. be "update_state"
}
int M2(args) {
X(foo);
/* here comes M2-specific code */
Z(bar);
}
Now, if I do the same in C++, X() and Z() no longer have access to the class' protected/private members. Swapping between .h and .cc file to declare those "helper" X() and Z() as I proceed with code writing somehow tempt me to just copy/paste the common code instead, so I tend to duplicate instead the class, having something that's closer to a (java) interface in .h -- with virtually no member variables -- and then have variables, API methods and "helper" methods all within a class block in the .cc file, that inherits from the "interface".
Yet, I doubt this is good practice with C++, so I'm curious to know what other people do in that case.
If X and Z are doing stuff relevant to the class, then make them member functions of the class (and if not, then there's no problem, since their implementations can easily be put elsewhere, out of public view).
If they're not supposed to be part of the public interface of the class, make them private.
If it bothers you that their function signatures show up in the class definition, then there are several ways to restructure your code, in such a way that implementation details aren't exposed.
A common way eg., is to use the Pimpl idiom.
Another way, would be to only expose (abstract) interfaces in the public API, and hide the implementing classes from view. This is not always possible, but when it is, it can be very effective.
If I understand you right what you want to achieve is to write the two functions X() and Z() only once for more than one function M(). Like the other comments suggest make them member functions marked as inline.
Additionally to implementing X() and Z() as member functions I would use the Strategy pattern where you have a function M() like this
class ClassTest
{
private:
void X();
void Y();
Alogrithm* m_algorithm;
public:
void M();
void setAlgorithm( Alogrithm* a ) { m_algorithm = a; }
}
void ClassTest::M()
{
X();
m_algorithm->execute();
Z();
}
This eliminates the need for a second function M2(). You only need to have a setter for m_algorithm which is a small object which implements your original function Y(). This way the algorithm can even be changed a runtime.
You could move your X and Z functionalities into private member function of your class and mark them with the inline modifier, if you wanted to. This would allow access to private members while making access from outside the class difficult.
I think you are wrong from concepts:
If X() and Z() have common code, this is a design improvement. Refactor them.
If M1(args) works ok, why are you changing it? Once you refactored X() and Z() you can use them in other method. Just create M2(args)using new X() and Z() plus new features in a new Y()method.
You can make the functions into:
Make them private members of the class.
Or you can put them within an anonymous namespace in the implementatio file.
With option #2 you will not be able to access the private members of the class, while this is a big issue, it can be mitigated by passing in all (and only) the required parameters, and either returning a value or using output parameters (pointers or references).
I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.