Let:
class CLASS{
void foo() {};
static void staticFoo() { foo(); }
};
Why would calling a nonstatic method from a static one be a problem? How do I go around this?
Judging by your question, it appears that you are not very familiar with object oriented programming. Writing C++ classes and not knowing object oriented programming is not the best idea. It's also not something we can sum up in a StackOverflow answer. It's best if you search for this topic and learn at least the basics before continuing. It actually would take less time that you'd imagine to get familiar with the basics.
This MIT class's presentation on object oriented programming is decent. Object oriented programming in C++
But to answer your question: why can't we call up a non-static method from a static method. Well when you define a C++ class, you're describing the model, or blueprint for making instances of something. For example, you could define a class Animal like this:
class Animal {
public:
void set_name(std::string name) { this->name_ = name; }
const std::string& get_name() const { return this->name_; }
private:
std::string name_;
};
We obviously have methods to set and get the name of this Animal class. Note that much like in the real world, we don't just name the abstract idea of animals, we'd name our own pet or some known specific animal, that happens to be one instance of an animal. This might receive criticism but you can kinda think of it as the difference between dog and the dog. The latter is a specific dog that all involved parties are aware of. That's why methods set_name and get_name need to know which animal you're talking about.
Consider this:
Animal my_dog;
my_dog.set_name("stripes");
Animal my_cat;
my_cat.set_name("katz");
The method set_name updates the name of my_dog and my_cat. We had to tell the set_name which instance we're talking about. Methods like these are instance methods, you can have a pointer to yourself which in C++ is designated by this. That's how you can update attributes about different instances. A static method doesn't receive this context and therefor won't be able to call instance methods unless of course it has access to one of these instances. For example:
static void print_animal(const Animal& animal) {
std::cout << animal.get_name() << std::endl;
}
After all of this, hopefully it makes sense why we can't just call Animal::set_name.
Why can't a nonstatic method be called from a static one?
A non-static member function can be called from a static member function.
Why would calling a nonstatic method from a static one be a problem?
It's not a problem. The problem is that you've not invoked the non-static member function on an object. Non-static member functions cannot be invoked without an object argument.
The syntaxes to invoke a non-static member function are following:
instance.mem_fun(arguments);
pointer->mem_fun(arguments);
Non-static member functions are special in that they can invoke other non-static member functions without explicit instance argument. The argument is implicitly this. Static member functions don't have this, and the exception doesn't apply to them.
How do I go around this?
Use one of the syntaxes shown above. You need to consider what instance you intend to use as the object argument of the non-static member function.
but why couldn't foo be called statically ...
Because foo is a non-static member function. Non-static member functions cannot be called statically.
... if the call is made from a static function?
Where the function is called from has no effect on whether it can be called statically.
Is there a way to call a non static class member method from another method that is contained within the main class in c++? If so, what would the code look like?
Problem is, I can't declare this specfic method as static, because it uses other methods within the same class that then don't work if I make the one static.
I'm trying to use:
MyClass::myClassMethod();
from a method within the main class, but it gives me the error: a non static member reference must be relative to a specific object.
To clarify, myClassMethod() uses other methods within MyClass like:
void myClassMethod() {
...
anotherClassMethod();
}
so if I were to make myClassMethod static it would interfere with calling anotherClassMethod().
What is the deal with calling non-static member function from a static member function?
Every non static member function is passed an this pointer implicitly in addition to the parameters you pass, the pointer passed is then dereferenced to refer class object members However static functions are not passed with the implicit thispointer and hence one cannot call any non static member function inside a static member function because there is no this to do so.
What is the solution, If you want to do it anyways?
You will need some mechanism to get the pointer to the object inside the static method and then you can call the member function using that pointer.
How to do that?
You will have to store the pointer to class object globally, or pass it as an instance in one of the function arguments to the static method.
However, both of above are workarounds, the important thing to note here is If you feel the need of calling a non static member function through a static member function then there is something wrong in your design.
On Second thoughts maybe I mis-read your Question before, Probably, Your question is:
How to call a non-static member function of a class from main?
You need a instance of the class to call non-static member functions.
So simply,
MyClass obj;
obj.myClassMethod();
And calling any other member function from within myClassMethod() would simply be:
void myClassMethod()
{
//...
anyOtherMyClassNonStaticMemberFunction();
//...
}
A static method is one that doesn't run on any particular object. It's a lot like a standalone function outside of a class, except that it's allowed to access private members in its class.
If you anotherClassMethod() is non-static, that means it has to be called on a specific object, an instance of the class. Because it's called on an object, it can access data stored in that object (non-static member variables). If myClassMethod() is static and you implement it as
void MyClass::myClassMethod() {
anotherClassMethod();
}
That won't work because anotherClassMethod() expects to be called on a specific object, but myClassMethod() doesn't have one. But if you know what object you want to call it on, you can do it as an ordinary method call on an object:
void MyClass::myClassMethod(MyClass &object) {
object.anotherClassMethod();
}
The object doesn't have to be passed in as an argument; it could be a static member variable in the class, for example:
class MyClass {
private:
static MyClass theInstance;
// ...
};
void MyClass::myClassMethod() {
theInstance.anotherClassMethod();
}
Ultimately, the question you need to ask yourself is: why is myClassMethod() static, and why is anotherClassMethod() non-static? Take a step back, think about what myClassMethod() is supposed to do. Does it make sense to call it when you don't have an instance to work with? If so, why does it need to call a method that expects to work with an instance?
The only way to call a non static method of a class is through an instance of that class. So you would need something like this...
MyClass myClass;
myClass.myClassMethod();
I think that maybe you could use the singleton pattern, keep a instance of the class in global. like a utility class.
From this reference:
(8.3.3/3) A pointer to member shall not point to a static member of a
class (9.4), a member with reference type, or "cv void."
Why a pointer cannot point to a static member of a class?
struct S {
static int f() { /*...*/ };
};
int main()
{
int (S::*s)() = &S::f; // why?
}
Why a pointer cannot point to a static member of a class?
Because for the purpose of membership it isn’t a member, merely for the purpose of scope. Apart from scope, static members are just like free functions, unattached to an instance of a class. You can use non-member function pointers:
int (*s)() = &S::f;
Whenever you do T::*, you're saying "this thing requires an instance of T to use." That statement does not hold for static functions, which are callable without any instances of the class.
You'd have to use a regular function pointer, like so:
int (*s)()=&S::f;
Like GMan said, static methods don't work on instances, so they don't receive the hidden this pointer. This effectively makes them have a different signature from instance methods with the same arguments.
I guess my question should be silly but it is true that I have never seen a function pointer that is declared as virtual. Is there a reason for this?
Edit:
I should have said: Is it possible that the function it points to is specified as virtual?
Well, yes (and no).
Ordinary function pointers cannot point to non-static member functions. They can only point to standalone functions, which is why for ordinary function pointers the matter of function virtuality does not even come into the picture.
In order to point to member functions in C++ you need a pointer of special kind: one that has pointer-to-member-function type. A pointer of this type can point to non-virtual member functions as well and to virtual member functions. There are no special steps to take if you want to point to virtual member function. For example
struct B {
virtual void foo() {}
void bar() {}
};
...
B b;
void (B::*pfunc)(); // declare a pointer to a member function
pfunc = &B::foo; // make it point to `B::foo`
(b.*pfunc)(); // calls `B::foo` for object `b`
pfunc = &B::bar; // make it point to `B::bar`
(b.*pfunc)(); // calls `B::bar` for object `b`
However, when you make such pointer to point to a virtual member function, you have to keep in mind that it is does not really get tied to a specific version of that function in the class hierarchy. The decision about the specific function to call is made at the point of the call. For example
// given the above `B`
struct D : B {
virtual void foo() {}
};
...
void (B::*pfoo)(); // declare a pointer to a member function
pfoo = &B::foo; // and make it point to `B::foo`
In the above example we made out pointer pfoo to point to B::foo. Or did we? In reality the pointer is not hard-linked to B::foo specifically. These two calls
B b;
D d;
(b.*pfoo)();
(d.*pfoo)();
will call two different functions. The first one will call B::foo for object b, while the second one will call D::foo for object d, even though we used the same pointer value in both cases. This makes sense actually in many applications.
Yet, in some low-level situation it would be useful to have a pointer that is hard-tied to a specific version of virtual function. I.e. it would be nice to have a pointer that would call B::foo for B subobject of object d when we do
(d.*pfoo)();
To achieve that we need to be able to specify whether we want to bind it early (at the point of initialization) or late (at the point of the call). Unfortunately, C++ language provides no such functionality.
A Function pointer is just a pointer to the function. It just stores address of an function just like any pointer to a type stores address of an type.
keyword virtual is used to implement polymorphic behavior(between functions of base class and derived class)through dynamic dispatch.
Given the above two are distinctly different and the idea of a function pointer to be virtual makes no sense at all.
whether the function it points to is specified as virtual ?
As I mentioned before an function pointer just stores address of an function. It is just an type. For eg:
int *i = NULL;
void doSomething();
typedef void(*ptr)() = NULL;
ptr = &doSomething();
In above example:
i is a type of int *. Similarly,
ptr is a type which can store address of an function which takes no parameter and returns no parameter.
So Yes, fundamentally, you can make the function to which a function pointer points as virtual, just like you would make any function virtual by declaring the particular function as virtual in the class.
The function pointer being a type can point to any function with that prototype, while declaring a function as virtual means having dynamic dispatch enabled on a particular function, as you see both are not the same.
Virtuality is a property of member functions. If you have a pointer to a virtual member function then a virtual call will be made automatically. Regular functions can't be virtual, so a virtual function pointer makes no sense. In either case there's no point making a function pointer virtual as its the function being pointed to that counts.
We make a non-member function a friend of a class when we want it to access that class's private members. This gives it the same access rights as a static member function would have. Both alternatives would give you a function that is not associated with any instance of that class.
When must we use a friend function? When must we use a static function? If both are viable options to solve a problem, how do we weigh up their suitability? Is there one that should be preferred by default?
For example, when implementing a factory that creates instances of class foo which only has a private constructor, should that factory function be a static member of foo (you would call foo::create()) or should it be a friend function (you would call create_foo())?
Section 11.5 "The C++ Programming Language" by Bjarne Stroustrup states that ordinary member functions get 3 things:
access to internals of class
are in the scope of the class
must be invoked on an instance
friends get only 1.
static functions get 1 and 2.
The question seems to address the situation where the programmer needs to introduce a function that does not work on any instance of a class (hence the possibility of choosing a static member function). Therefore, I will limit this answer to the following design situation, where the choice is between a static function f() and a friend free function f():
struct A
{
static void f(); // Better this...
private:
friend void f(); // ...or this?
static int x;
};
int A::x = 0;
void A::f() // Defines static function
{
cout << x;
}
void f() // Defines friend free function
{
cout << A::x;
}
int main()
{
A::f(); // Invokes static function
f(); // Invokes friend free function
}
Without knowing anything in advance about the semantics of f() and A (I'll come back to this later), this limited scenario has an easy answer: the static function is preferable. I see two reasons for this.
GENERIC ALGORITHMS:
The main reason is that a template such as the following can be written:
template<typename T> void g() { T::f(); }
If we had two or more classes that have a static function f() on their interface, this would allow us writing one single function that invokes f() generically on any such class.
There is no way to write an equivalent generic function if we make f() a free, non-member function. Although it is true that we could put f() into a namespace, so that the N::f() syntax could be used to mimic the A::f() syntax, it would still be impossible to write a template function such as g<>() above, because namespace names are not valid template arguments.
REDUNDANT DECLARATIONS:
The second reason is that if we were to put the free function f() in a namespace, we would not be allowed to inline its definition directly in the class definition without introducing any other declaration for f():
struct A
{
static void f() { cout << x; } // OK
private:
friend void N::f() { cout << x; } // ERROR
static int x;
};
In order to fix the above, we would to preceed the definition of class A with the following declaration:
namespace N
{
void f(); // Declaration of f() inside namespace N
}
struct A
{
...
private:
friend void N::f() { cout << x; } // OK
...
};
This, however, defeats our intention of having f() declared and defined in just one place.
Moreover, if we wanted to declare and define f() separately while keeping f() in a namespace, we would still have to introduce a declaration for f() before the class definition for A: failing to do so would cause the compiler to complain about the fact that f() had to be declared inside namespace N before the name N::f could be used legally.
Thus, we would now have f() mentioned in three separate places rather than just two (declaration and definition):
The declaration inside namespace N before A's definition;
The friend declaration inside A's definition;
The definition of f() inside namespace N.
The reason why the declaration and definition of f() inside N cannot be joined (in general) is that f() is supposed to access the internals of A and, therefore, A's definition must be seen when f() is defined. Yet, as previously said, f()'s declaration inside N must be seen before the corresponding friend declaration inside of A is made. This effectively forces us to split the declaration and the definition of f().
SEMANTIC CONSIDERATIONS:
While the above two points are universally valid, there are reasons why one might prefer declaring f() as static over making it a friend of A or vice versa which are driven by the universe of discourse.
To clarify, it is important to stress the fact that a member function of a class, whether it is static or non-static, is logically part of that class. It contributes to its definition and thus provides a conceptual characterization of it.
On the other hand, a friend function, in spite of being granted access to the internal members of the class it is friend of, is still an algorithm which is logically external to the definition of the class.
A function can be friend of more than one class, but it can be member of just one.
Thus, in a particular application domain, the designer may want to keep into consideration the semantics of both the function and the class when deciding whether to make the former a friend or a member of the latter (this applies not only to static functions, but to non-static functions as well, where other language constraints may intervene).
Does the function logically contribute to characterize a class and/or its behavior, or is it rather an external algorithm? This question can't be answered without knowledge of the particular application domain.
TASTE:
I believe that any argument other the ones just given stems purely from a matter of taste: both the free friend and the static member approach, in fact, allow to clearly state what the interface of a class is into one single spot (the class's definition), so design-wise they are equivalent (modulo the above observations, of course).
The remaining differences are stylistic: whether we want to write the static keyword or the friend keyword when declaring a function, and whether we want to write the A:: class scope qualifier when defining the class rather than the N:: namespace scope qualifier. Thus, I will not comment further on this.
The difference is clearly expressing the intent of the relationship between the class and the function.
You use friend when you want to intentionally indicate a strong coupling and special relationship between two unrelated classes or between a class and a function.
You use static member function when the function is logically a part of the class to which it is a member.
Friend functions (and classes) can access the private and protected members of your class.
There's rarely a good case for using a friend function or class. Avoid them in general.
Static functions may only access static data (that is, class-scoped data). They may be called without creating an instance of your class. Static functions are great for circumstances you want all of the instances of your class to behave the same way. You can use them:
as callback functions
to manipulate class-scoped members
to retrieve constant data that you don't want to enumerate in your header file
Static functions are used when you want a function that is the same for every instance of a class. Such functions do not have access to "this" pointer and thus cannot access any non static fields. They are used often when you want a function that can be used without instantiating the class.
Friend functions are functions which are not in the class and you want to give them access to private members of your class.
And this(static vs. friend) is not a matter of using one vs the other since they are not opposites.
The standard requires that operator = () [] and -> must be members, and class-specific
operators new, new[], delete and delete[] must be static members. If the situation
arises where we don't need the object of the class to invoke a function, then make
the function static. For all other functions:
if a function requires the operators = () [] and -> for stream I/O,
or if it needs type conversions on its leftmost argument,
or if it can be implemented using the class' public interface alone,
make it nonmember ( and friend if needed in the first two cases)
if it needs to behave virtually,
add a virtual member function to provide the virtual behaviour
and implement in terms of that
else
make it a member.
Static function can only access members of one class. Friend function has access to several classes, as explained by the following code:
class B;
class A { int a; friend void f(A &a, B &b); };
class B { int b; friend void f(A &a, B &b); };
void f(A &a, B &b) { std::cout << a.a << b.b; }
f() can access data of both A and B class.
One reason to prefer a friend over static member is when the function needs to be written in assembly (or some other language).
For instance, we can always have an extern "C" friend function declared in our .cpp file
class Thread;
extern "C" int ContextSwitch(Thread & a, Thread & b);
class Thread
{
public:
friend int ContextSwitch(Thread & a, Thread & b);
static int StContextSwitch(Thread & a, Thread & b);
};
And later defined in assembly:
.global ContextSwitch
ContextSwitch: // ...
retq
Technically speaking, we could use a static member function to do this, but defining it in assembly won't be easy due to name mangling (http://en.wikipedia.org/wiki/Name_mangling)
Another situation is when you need to overload operators. Overloading operators can be done only through friends or non-static members. If the first argument of the operator is not an instance of the same class, then non-static member would also not work; friend would be the only option:
class Matrix
{
friend Matrix operator * (double scaleFactor, Matrix & m);
// We can't use static member or non-static member to do this
};
A static function is a function that does not have access to this.
A friend function is a function that can access private members of the class.
You would use a static function if the function has no need to read or modify the state of a specific instance of the class (meaning you don't need to modify the object in memory), or if you need to use a function pointer to a member function of a class. In this second instance, if you need to modify the state of the resident object, you would need to pass this in and use the local copy. In the first instance, such a situation may happen where the logic to perform a certain task is not reliant on an object's state, yet your logical grouping and encapsulation would have it be a member of a specific class.
You use a friend function or class when you have created code that is not a member of your class and should not be a member of your class, yet has a legitimate purpose for circumventing the private/protected encapsulation mechanisms. One purpose of this may be that you have two classes that have need of some common data yet to code the logic twice would be bad. Really, I have only used this functionality in maybe 1% of the classes I've ever coded. It is rarely needed.
A friend function can not be inherited while a static function can be. So when an aim can be achieved with both static function and friend function, think that whether you want to inherit it or not.
Static function can be used in many different ways.
For example as simple factory function:
class Abstract {
private:
// no explicit construction allowed
Abstract();
~Abstract();
public:
static Abstract* Construct() { return new Abstract; }
static void Destroy(Abstract* a) { delete a; }
};
...
A* a_instance = A::Conctruct();
...
A::Destroy(a_instance);
This is very simplified example but I hope it explains what I meant.
Or as thread function working with Your class:
class A {
public:
static void worker(void* p) {
A* a = dynamic_cast<A*>(p);
do something wit a;
}
}
A a_instance;
pthread_start(&thread_id, &A::worker, &a_instance);
....
Friend is completely different story and they usage is exactly as described by thebretness
Friend functions can access the private and protected members of other classes.
Means they can be used to access all the data weather it is private or public.
So friend functions are used to access that data which static methods can not.
Those methods are made static which are called so many times that declaring a different location inside every object, for them becomes too costly(In terms of memory).
This can be made clear with the help of example:
Let the class's name is fact and its data member is n(which represents integer whose factorial is concern)
then in this case declaring find_factorial() as static would be wise decision!!
They are used as callback functions
to manipulate class-scoped members
to retrieve constant data that you don't want to enumerate in your header file
Now we are clear with following questions..
When a friend function is used? When a static function is used?
Now If both are viable options to solve a problem,
We can weight up their suitability in terms of accessibility(accessibility of Private data) and memory efficiency.
By default no one can be preferred as there are many situation when we need better memory management and sometimes we are are concerned with the scope of data.
For example:
foo::create() will be preferred over create_foo() when we have to call create() method after every small instance of time and we are not interested on scope of data(Private data)
And if we are interested to get the private information of more than one class(s) then create_foo() will be preferred over foo::create().
I hope this would help you!!
Here is what I think it is:
Friend function- when you need access to a different class member, but the classes are not related. Static function- when you no not need access to the 'this' pointer. But, I have a feeling there is more to it....
Static data members always share the memory.
only static function can used static data members.
static member function can be called with class name.
They must be defined outside of the class when we create a object of static member or member function in the class. It will automatically initialize the value.
It always used keyword static.
Static members can share by all the objects.
Type and scope of data members and member function is outside of the class.
A static member variable must be defined outside of the class.