Is it possible to make a class which does not need to be instantiated? In other words, is it possible to use functions of that class without having an instance of it?
You can use static functions, those are bound to the Class, not an instance.
class Test{
static void
doSomething()
{
std::cout << "something" << std::endl;
}
}
int
main(int argc, char** argv)
{
Test::doSomething(); //prints "something" without instance of Test
}
Otherwise you could build a Singleton, in which case the class itself would hold the instance, but I am not sure if this is what you wanted to know...
You could make all member functions and variables static, but then one starts to wonder why it should be a class, and not a namespace.
There is a good reason, though: you may want to use a class template like this. C++14 will add variable templates, which make the same possible without a class. A class also allows access control; you can fake this for the non-template case with anonymous namespaces, but a class may be more natural.
A static method can be called without creating an instance of the class.
class CMyClass
{
public:
static void Method1()
{
printf("Method1\n");
}
};
CMyClass::Method1(); // Prints "Method1".
Yes, it is possible. If you want to use of class without having instance of it, you must use static functions.
You can also create private constructor of such class with static methods to prevent from creating any instances
For that you should use the static modifier. See documentation here: http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
Related
EDIT: No... I dont wanna use :: I want to be able to use . when using static method
EDIT 2: Not a namespace. A class/struct is what I'm trying to use!
I bet this has been asked and answered before but I cant find an answer
Suppose I have a class called "A"
struct A {
void log(const char* x) {
std::cout << x << std::endl;
}
}
If i want to use this class i need to do something like A B;
Then i can do something like B.log("Hello World!");
But is there any possible way I dont have to make an object to use a class? I just want to be able to do A.log("Hello World!");
Is that possible?
Can you use a class without objects?
Yes, you can. For example, you can access static members of a class.
I want to be able to use . when using static method
You cannot do what you want. The member access operator . can only be used on values of the class type and for that you need an object. The operator to access static member function of a class without an object is the scope resolution operator ::.
You also cannot call a non-static member function - such as A::Log of your example - without an instance regardless of syntax.
An alternative to using a class could be to use a namespace instead:
namespace A {
void log(const char* x) {
std::cout << x << std::endl;
}
}
That way, your class doesn't need to exist, it can just be a free-function inside it's own namespace. You even call it the same way:
A::log("foo");
You need to change your code as follows,
class A {
static void log(const char* x) {
std::cout << x << std::endl;
}
}
//Call it as follows,
A::log("hello");
Observe the word, static. static methods are class level methods and should be called via class. You will not be able to call it with objects of the class A.
You can use struct instead of class if you like :-)
But is there any possible way I dont have to make an object to use a class? I just want to be able to do A.log("Hello World!");
To use that syntax, you need an object.
With a small change, you can have your expected syntax:
/*inline*/ struct {
void log(const char* x) {
std::cout << x << std::endl;
}
} A;
Demo
Anonymous class, with variable A of that type.
If put in header included at several place, adding inline or static would avoid ODR-violation.
Using regular way (static method and A::log) is less surprising.
I'm currently trying to implement a factory design pattern and somewhat confused as to how this is typically done in C++. I've been referring to this webpage.
So on that webpage, they show an example where they define a factory class called ComputerFactory. This class has a single NewComputer method which is static.
class ComputerFactory
{
public:
static Computer *NewComputer(const std::string &description)
{
if(description == "laptop")
return new Laptop;
if(description == "desktop")
return new Desktop;
return NULL;
}
};
The fact that NewComputer is static means it's not associated with a single instance of ComputerFactory. Thus it is possible to call this method from your code by writing
ComputerFactor::NewComputer("description");
Now I'm curious as to why this needed to be wrapped within a class. Because it's static and really isn't meant to be associated with any class, it would make more sense to do something like
namespace ComputerFactory
{
static Computer *NewComputer(const std::string &description)
{
if(description == "laptop")
return new Laptop;
if(description == "desktop")
return new Desktop;
return NULL;
}
}
So my questions:
Is the namespace function I described a valid alternative?
Would it ever make sense to define a class that only has static methods? It seems like it would make more sense to use a namespace.
Now I believe there are instances where it would make sense to have static methods (e.g. static 'how many of these classes currently exist'), but this doesn't appear to be a situation where it's necessary. Any thoughts?
Edit: So I just had a thought, the example I listed isn't a 'typical' factory method. In practice, it's possible that the factory function is more complex and requires calling other functions (private class methods). In this case, it would make complete sense to wrap the factory into a class such that you could access subfunctions. Is this why factory methods are typically wrapped into classes?
Is the namespace function I described a valid alternative?
Yes
Would it ever make sense to define a class that only has static methods? It seems like it would make more sense to use a namespace.
If the methods are utility methods that can be utilized in many classes, then it would make more sense for them to be in namespace.
If the methods are specific to the class then make them static inside the class itself, which would result in better encapsulation.
Is the namespace function I described a valid alternative?
Yes.
Would it ever make sense to define a class that only has static methods? It seems like it would make more sense to use a namespace.
There are things you can do with a class that you cannot do with a namespace.
You mentioned one of them (to make use of private members, even though you can use an anonymous namespace to do something similar - not so good actually).
Another relevant example is that you cannot templatize a namespace and this can be quite annoying.
As an example, this happens with a class:
template<typename T>
struct S {
static T f() { return T(); }
// Other member functions
};
// ...
using MyS = S<int>;
MyS::f();
This happens with a template:
namespace N {
template<typename T>
T f() { return T(); }
// Other function template
}
// ...
N::f<int>();
In other terms, you can only define function template if you are using a namespace and it could not be the best solution in any situation.
Moreover, you cannot create an alias as you can do with your class, so you must be explicit about the types at any call place and it can be error-prone and difficult to refactor.
I wrote the following code:
class A
{
public:
int cnt;
static void inc(){
d.cnt=0;
}
};
int main()
{
A d;
return 0;
}
I have seen this question:
How to call a non static member function from a static member function without passing class instance
But I don't want to use pointer. Can I do it without using pointers?
Edit:
I have seen the following question:
how to access a non static member from a static method in java?
why can't I do something like that?
No, there is no way of calling a non-static member function from a static function without having a pointer to an object instance. How else would the compiler know what object to call the function on?
Like the others have pointed out, you need access to an object in order to perform an operation on it, including access its member variables.
You could technically write code like my zeroBad() function below. However, since you need access to the object anyway, you might as well make it a member function, like zeroGood():
class A
{
int count;
public:
A() : count(42) {}
// Zero someone else
static void zeroBad(A& other) {
other.count = 0;
}
// Zero myself
void zeroGood() {
count = 0;
}
};
int main()
{
A a;
A::zeroBad(a); // You don't really want to do this
a.zeroGood(); // You want this
}
Update:
You can implement the Singleton pattern in C++ as well. Unless you have a very specific reason you probably don't want to do that, though. Singleton is considered an anti-pattern by many, for example because it is difficult to test. If you find yourself wanting to do this, refactoring your program or redesigning is probably the best solution.
You cannot use non-static member variables or functions inside a static function without using pointers.
You don't need a pointer per se, but you do need access to the object through which you are accessing the non-static variable. In your example, the object d is not visible to A::inc(). If d were a global variable rather than a local variable of main, your example would work.
That said, it's curious why you'd want to go to any great effort to avoid using pointers in C++.
The question is, what would be the best or maybe a better practice to use. Suppose I have a function, which belongs to some class and this function needs to use some static variable. There are two possible approaches - to declare this variable as class's member:
class SomeClass
{
public:
....
void someMethod();
private:
static int m_someVar;
};
SomeClass::someMethod()
{
// Do some things here
....
++m_someVar;
}
Or to declare it inside the function.
class SomeClass
{
public:
....
void someMethod();
};
SomeClass::someMethod()
{
static int var = 0;
++m_someVar;
// Do some things here
....
}
I can see some advantages for the second variant. It provides a better encapsulation and better isolates details of an implementation. So it would be easier to use this function in some other class probably. And if this variable should be modified only by a single function, then it can prevent some erroneous data corruption from other methods.
While it's quite obvious, that the first variant is the only one to use when you need to share a static variable among several methods (class functions), the question pertains the case when a static variable should be used only for a single function. Are there any advantages for the first variant in that case? I can think only about some multi threading related stuff...
It's simple - use a static member if, logically, it belongs to the class (sort of like instanceCounter) and use a static local if it logically belongs to a function (numberOfTimesThisMethodWasCalled).
The choice of static or not depends completely on the context. If a particular variable needs to be common among all the instances of a class, you make it static.
However, if a variable needs to be visible only in a function and needs to be common across every call of the function, just make it a local static variable.
The difference between static data members and static variable in a function is that first are initialized at start-up and the second first time the function is called (lazy initialization).
Lazy initialization can create problem when a function is used in a muti-threaded application, if it is not required by the design I prefer to use static members.
#include <iostream>
using namespace std;
class MyClass
{
public:
void printInformation();
};
void MyClass::printInformation()
{
return;
}
int main()
{
MyClass::printInformation();
fgetc( stdin );
return(0);
}
How would I call the printInformation function within main?
The error tells me that I need to use a class object to do so.
Declare an instance of MyClass, and then call the member function on that instance:
MyClass m;
m.printInformation();
From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.
Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.
class MyClass
{
public:
static void printInformation();
};
Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.
Myclass m;
m.printInformation();
// Or, in the case that you want to use pointers:
Myclass * m = new Myclass();
m->printInformation();
If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
Please note that in the current case you would not need a pointer. :-)
If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.
If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.
declare it "static" like this:
static void MyClass::printInformation() { return; }
You need to create an object since printInformation() is non-static. Try:
int main() {
MyClass o;
o.printInformation();
fgetc( stdin );
return(0);
}
you have to create a instance of the class for calling the method..
On an informal note, you can also call non-static member functions on temporaries:
MyClass().printInformation();
(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))