ok, so my problem is this. I need to copy a custom made list and the function has to be a private member of my list-class. looks like this atm:
private:
struct List_Node* head_;
List* copy(List* list);
looks like crap i know, but i have been told to do it that way.
getting the compilation error:
error: `List* List::copy(List*)' is private
is there some way to go around this problem or am i understanding my directions wrong?
You need to call the function from within another member function which is public.
You cannot call private member functions from outside the class. The error suggests you are doing that.
If you are calling the List::copy from within member functions of List (as the title indicates), you should have no problem.
If you want to call it from outside the class, you will not get access to the private member functions (e.g. copy) unless you declare the caller function a friend of the class
Try to use copy-constructor or operator = overloading.
I think you are told to do so because the users of this class are not supposed to copy the list directly. The list node is also declared as a private structure, which is inaccessible to outside functions. The construction and destruction of the list node should be handled by member methods of this class.
May be because of these reasons, the copy method should be protected, in this case, declared as private.
You can call the private copy method in any member methods of this class, including public methods.
Although it is unlikely to happen, you can simply declare a public member method only calling this private method, which expose the private method to outside functions. However, it will be non-sense to declare the copy method private in the first place.
Related
How can we prevent friend function from accessing private member of a class. Can we do this at all?
This question was asked in an interview and he was confident that it can be done, he gave hint about functor / function object. So far I can't think of anything. I am excited about the answer, if any.
How can we prevent friend function from accessing private member of a class. Can we do this at all?
No, you cannot.
As soon something is declared as friend of your class the doors to access any private members are opened.
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members.
I have a class that I'm refactoring it and would like to add a helper function to eliminate some code duplication in both static and non-static methods, so the helper function must be static. When I go to call the helper function from inside the non-static method, will I need to use the double colon notation, MyClass::helper_function(x, y, z), the arrow notation, this->helper_function(x, y, z), or just helper_function(x, y, z)? If the helper function was public would you be able to access it from an instance with the dot notation, myObject.helper_function(x, y, z)? I'll try it out in a couple of minutes, and I'm sure I'll figure it out, but I thought it was a good gedankenexperiment to try to figure out what will happen.
Should I just make the helper function not a member of the class at all, but just put it in the class's .cpp file to make it accessible to the class's methods? What is the best practice?
All three formats work.
MyClass::helper_function - this is a Qualified Name. The class name is looked up first, finds the current class, and then the static method is found in the class.
helper_function - this is an unqualified name. it will be looked up in the class scope first, before the surrounding scope would be tried. But since helper_function is a static method in the class, no further searches are done
this->helper_function - This is the most unusual of all. The this pointer has type MyClass*, so the search is restricted to MyClass. But once helper_function is found, it turns out that the this pointer isn't actually needed. That doesn't invalidate the name lookup.
Class member or not?
A static helper function may access other class members, in particular private members. This includes private constructors, private destructors, private nested types, constants, etc. If you need one of them, a static method is the only reasonable choice.
Yes, you can access static methods by way of the this pointer and the . or -> notation.
This question is similar, but is about calling the function from inside the class: Can I call a base class's virtual function if I'm overriding it?
In that case, you'd specify Base::function() instead of function(), which will call the overridden definition.
But is there a way to do this outside of the class? My class doesn't define a copy constructor, so I couldn't figure out how to cast as the base class:
Base( derived_object ).function()
Is the appropriate thing to do here to cast & derived_object as Base* and then call ->function()?
Thanks for your insight.
Try derived_object.Base::function();
I believe the syntax:
derived_ptr->Base::function();
works just fine. Though I really question why you would want to do this in a function that's not part of your class. Especially if function happens to be a virtual function.
The reason why it's a questionable idea is that you're making whatever it is that uses that notation depend on the inheritance hierarchy of your class. Also, functions are usually overridden for a reason. And you're getting around that by using this syntax.
You probably want to use pointers to member functions of a class. Those give you the ability to map different base class functions to the pointer as needed, and the ability to use it as a variable or function parameter.
The syntax for a pointer to a member function looks like
class Base
{
public:
virtual bool Function();
virtual bool OtherFunction();
};
typedef bool (Base::*)() BaseFunc;
The list of caveats for using these things is a mile long- there is plenty online on how to use them (most of the answers are "don't"). However, they do give you a way of clearly binding to and calling a base class member function.
I have a class with two member functions that share a piece of code:
void A::First()
{
firstFunctionEpilogue();
sharedPart();
}
void A::Second()
{
secondFunctionEpilogue();
sharedPart();
}
Currently firstFunctionEpilogue(), secondFunctionEpilogue() and sharedPart() are not function calls but just pieces of code, sharedPart() code being duplicated. I want to get rid of the duplication.
The shared piece of code doesn't need access to any members of the class. So I can implement it as any of the three:
a static member function,
a const non-static member function or
a local function.
Which variant is better and why?
If your function accesses state but does not change it then use a const member function.
Your case:
If it your function 1) doesn't need access to any member of the code, and 2) is related to that class, then make it a static function of your class.
That way it is clear that it is not modifying state, nor based on the state of the object.
An extra case you didn't mention:
There is another thing you can do too. And that is to make your SharedPart take in a member function pointer and to call it and then process it's main body. If you have a lot of First(), Second(), Third(), Fourth(), ... such functions then this can lead to less code duplication. That way you don't need to keep calling SharedPart(); at the end of each member function, and you can re-use First(), Second(), THird(), ... without calling the SharedPart() of the code.
I'd say:
It probably doesn't matter, so it's not so much "best practice" as "just don't do anything crazy".
If the class and all its members are defined in its header, then a private static member function is probably best, since it clearly indicates "not for clients". But there are ways to do this for a non-member function: don't document it, put in a comment "not for clients", and stick the whole thing in namespace beware_of_the_leopard.
If the class member functions are defined in a .cpp file, then little helper functions like this are best as free functions in the .cpp file. Either static, or in an anonymous namespace.
Or it could be in a different class.
Or, if it's a member, it could be virtual.
There are a lot of decisions, and I wouldn't stress out about it too much. Generally, I opt for a const non-static member function as a default unless I have a good reason not to do it that way.
Prefer static if clients need to call it without having an instance
Prefer local functions if you don't want to clutter the .h file or you want it completely hidden in the .c
Make it a non-member function
The shared piece of code doesn't need access to any members of the class.
As a general rule, if a piece of code doesn't need access to any members of the class don't make it a member function! Try to encapsulate your classes as much as possible.
I'd suggest doing a non-member function in a separate namespace that would call the public methods and then call the function you made for the shared code.
Here is an example of what I mean :
namepsace Astuff{
class A{...};
void sharedPart(){...};
void first(const A& a);
void second(const A& a);
}
void Astuff::first(const A& a){
a.first();
sharedPart();
}
a static member function, a const
non-static member function or a local
function.
Generally, it should be a member function of another class, or at least non-static member of the class itself.
If this function is only called from instance members of a class - probably its logical meaning requires an instance, even if syntax does not. Can anything except this object provide meaningful parameters or make use of the result?
Unless it makes sense to call this function from outside of the object instance, it shouldn't be static. Unless it makes sense to call this function without accessing your class at all, it shouldn't be local.
Borrowing examples from Brian's comment:
if this function changes global state, it should be member of a class of global state;
if this function writes to file, it should be member of a class of file format;
if it's refreshing screen, it should be member of... etc
Even if it's a plain arithmetic expression, it may be useful to make it a member (static or not) of some ArithmeticsForSpecificPurpose class.
Make it a non-member non-friend function. Scott Meyer's has a great explanation for this here (and also Item 23 of Effective C++ 3rd Edition).
As a rule of thumb "try to keep it as local as possible but as visible as necessary".
If all code calling the function resides in the same implementation file, this means keeping it local to the implementation file.
If you'd make it a private static method of your class, it would not be callable by implementaions including your class, but it would still be visible to them. So every time you change the semantics of that method, all implementaions including your calls will have to recompile - which is quite a burden, since from their point of view, they don't even need to know those sementics.
Thus, in order to minimize unnecessary dependencies, you would want to make it a static global function.
However, if you should ever find yourself repeating this global function in mulitple implementation files, it would be time to move the function into a seperate header/implementaion file pair, so that all callers can include it.
Whether you place that function into a namespace, at global scope, or as a static function in a class is really up to taste.
On a final note, if you go for the global static function, there's a "more c++ like" version: anonymous namespaces. It has the nice property that it can actually store state and also prevents users for being able to even forward declare any of its functions.
// in your .cpp file
namespace /*anonymous*/
{
void foo()
{
// your code here
}
};
void MyClass::FooUser1() { foo(); }
void MyClass::FooUser2() { foo(); }
All the member variables and member functions in my class ClassA are static.
If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class.
Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object?
Thank you
Instead of using a class with all static methods, you may be better off making the methods free-standing functions in a separate namespace. The call syntax would be the same:
namespace::function() instead of classname::function()
and you don't need to deal with someone trying to instantiate your class.
Creating a private default constructor should be sufficient. Both of the other default constructs (copy constructor and assignment) rely on having an instance to work correctly. If there is no default constructor then there is no way to create an instance, hence no way to actually get to the copy construction part.
It would likely save you a few headaches though to define all 3 as private and not implemented.
Like others said, a namespace is what you should use. If you want to stay with your class, create a class that has a private constructor, and derive from it, to make your intention obvious:
class NonConstructible {
NonConstructible();
};
class SuperUtils: NonConstructible {
static void foo();
// ...
static std::vector<int> globalIDs;
// ...
};
Ok, now let's look into the namespace which are the one and only way to do this:
namespace SuperUtils {
void foo() {
// ....
}
std::vector<int> globalIDs;
};
You can call that using SuperUtils::foo(); in both cases, but the namespace has the advantage that in a scope you can use the namespace declaration and directive to bring certain or all members into the current scope, so that you can reference them without using SuperUtils:::
void superFunction() {
using namespace SuperUtils;
foo();
}
While generally that should be avoided, it can be helpful when the method is using exclusively much stuff from SuperUtils, which then can improve the readability of the code.
In order to use a copy constructor you have to have an object to copy, so if you've locked down the default constructor you should be safe.
The best way to prevent creation of non-heap objects is to make destructor private. Then there is no way compiler can destruct the object when it goes out of scope and it will complain.
This will not prevent anyone from doing new however.