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.
Related
I have a class foo with two methods:
static void BuildToto(...);
void BuildToto(...);
The two methods have exactly the same prototype except that one is static while the other is not.
In a third method of the same class, I want to call the static method and not the other one. So, naively, I wrote this:
foo::BuildToto();
But while debugging, it becomes clear the code executes like the pointer this was present in the line above. How can I call the static method explicitly?
You can't: overload resolution will fail as no syntax can be employed to distinguish them.
One way around it, other than renaming one of the functions, would be to templatise one of the functions:
#include <iostream>
using namespace std;
struct Foo
{
template<typename> void foo(int n) const {
std::cout << "member\n";
};
static void foo(int n){
std::cout << "static\n";
}
};
int main() {
Foo::foo(1); // static
Foo f;
f.foo<void>(1); // member
}
ok, i solve the mystery:
My two methods haven't the same exact prototypes except one has a vector among its input while the other one has a smart_pointer on vector.
Unfortunately, i call the wrong version by not dereferencing the sp. So there was no compiler error. The fact the two methods share the same name and almost the same prototype just drove to my issue.
So i will take care to add a little suffixe to the static version of the methods to avoid any future confusion...
Any idea for a suffixe to the static method's name ?
Can the same function be defined differently for different objects of the same class??
in A.h
class Hello{
public:
void myfunction();
}
main.cpp
Hello B0,B1;
// Here I want to define the function 'myfunction' for each object differently
int main(){
B0.myfunction();
B1.myfunction();
}
Is this possible?
Not directly, and I'd wonder why you want to do that if you really do want them to be objects of the same class type? This is what inheritance and virtual functions are for! If you want them to behave differently, you should make them different (but related) classes.
That said, I can think of one way to achieve something like this. std::function.
Have a class member like std::function<void(Hello*)> myfunctionimpl;, and then a member function void myfunction() { myfunctionimpl(this); }
Then in the constructor of Hello, you can set myfunctionimpl as a pointer to some other function, or with a lambda. For example, the following:
#include <functional>
#include <iostream>
class Hello {
public:
typedef std::function<void(Hello*)> MyFunctionType;
private:
MyFunctionType myfunctionimpl; // this holds the customisable function object
public:
Hello(const MyFunctionType& mf) // construct with a custom function object passed in
: myfunctionimpl(mf)
{}
Hello() // construct with a default function object
: myfunctionimpl([](Hello *h) {
std::cout << "Default function called on " << h << '\n';
})
{}
Hello(int){} // dummy to leave function object unset
void myfunction() {
// call the function object, only if it is safe to do so
if (this->myfunctionimpl) {
this->myfunctionimpl(this);
}
else {
std::cerr << "myfunctionimpl not set!\n";
}
}
};
void freeFunction(Hello*)
{
std::cout << "freeFunction\n";
}
int main()
{
Hello h1; // default
Hello h2(1); // not set
Hello h3(freeFunction); // custom function
h1.myfunction();
h2.myfunction();
h3.myfunction();
}
prints:
Default function called on 0x7fffa12518e0
myfunctionimpl not set!
freeFunction
So here the member function myfunction behaves the same way for every instance; calls the myfunctionimpl function object (if it is set). But you can customise the function object that is called for each instance, since that is just class data.
The default constructor demonstrates use of lambdas, which allow you to write small functions in place, which is probably what you will want to do to provide custom behaviour when each object is constructed. There are lots of tutorials for lambdas, for instance.
No, a member function of all instances of the same class behave the same. However, the behaviour can depend on the state of the object. For example, you could store a function pointer in a data member and call the pointed function in the member function. So, the member function does exactly the same thing for each instance: calls the function pointed by the member, but the observed behaviour may be completely different if the pointed function is different.
Also, if the function is virtual, then instances of different subclasses can override the virtual function differently.
As from your comment
I am trying to create a kind of framework using c++ and opengl. Suppose i have a object of a class lets say Button which has a function onClick. On clicking button different users should be able to define the function in their own way.
See here for an excellent article by Herb Sutter on the subject of virtuality, since that is what you would look for when considering to build functionality described in your question and building framework.
The questions are old, but people still keep asking them,
One building framework could be interested on
Polymorphism pointers and class inheritance;
Virtual functions a member functions whose behavior can be overridden in derived classes.
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
When using encapsulation and "tell, don't ask"-principle properly, there should be no reason for one to ask information from an object.
However, I've ran into a situation (let me know if this design itself is terrible) where I have an object with a member variable pointing to a function outside of the class.
At some point of my application, there's a need for my object to call the function and the function should then act based on my object's status.
Here's an example class:
typedef void(*fptr)(Foo*);
class Foo {
public:
Foo(string name, fptr function);
void activate()
{
m_function(this);
}
private:
string m_name;
fptr m_function;
};
That's the class, now the developer can use the class like so;
void print(Foo *sender)
{
cout << "Print works!" << endl;
}
int main(int argc, char **argv)
{
Foo foo("My foo", &print);
foo.activate();
// output: "Print works!"
}
This all works fine, but what if I want to print the name of the sender?
All the functions are defined outside of the class, by other developers, so there's no way to access private variables.
In C#, you can just use the partial keyword to add a method to an existing class.
This is not possible in C++ though.
I could just ignore encapsulation and create a setter and getter for name and all other properties that might be needed by the function in the future.
This is pretty terrible solution, I should basically create setter and getter for everything there is in my class, since the function can do anything to my object.
Besides what's the reason of encapsulation, if I'm just gonna ignore it when I want to?
An other solution would be a struct that holds the required properties inside it:
struct FooBar {
string name;
};
typedef void(*fptr)(FooBar);
void Foo::activate()
{
FooBar fb;
fb.name = m_name;
m_function(fb);
}
But this is not much different from not using encapsulation, and it doesn't seem like a too good solution either.
What would be the best approach for this problem?
I would make activate() an abstract method and all the class' properties protected.
Also, there's no need for the fptr:
class Foo {
public:
Foo(string name);
virtual void activate() = 0;
protected:
string m_name;
};
Now when someone wants to use your class, he just inherits his own from it:
class MyFoo : public Foo {
public:
MyFoo(string name);
virtual void activate()
{
cout << m_name << " says: Hello World!" << endl;
}
};
int main(int argc, char **argv)
{
MyFoo foo("My foo");
foo.activate();
// output: "My Foo says: Hello World!"
}
And if you need many different Foo's with different functionality, just inherit multiple classes instead of declaring multiple functions.
Edit: Instead of inheriting a new class for every different Foo instance, you could inherit one class for all of them with all the different methods.
Now all left for activate is to decide which method to call; use enum for this:
enum MyFooFunction {
printName,
printHello
};
class MyFoo : public Foo {
public:
MyFoo(string name, MyFooFunction function);
void printName() { cout << m_name << endl; }
void printHello() { cout << "Hello!" << endl; }
virtual void activate()
{
switch(m_function) {
case printName:
printName();
break;
case printHello:
printHello();
break;
}
}
protected:
MyFooFunction m_function;
};
Seen from the outside, private variables don't exist, so developers cannot possibly "want" to print them.
If they do want then either the class members (or better, queries in the class returning their contents) should be public, the function a member of the class, or in specific cases some friend mechanism may be used.
To summarize, don't set out to break encapsulation - instead, reconsider the abstraction behind your encapsulation and, if needed, create new queries for properties of your class which weren't foreseen as useful back when the class was designed - but now are.
You might want to change your function parameter type to const string & if the function should be able to see the string, but the rest of the outside world shall not see it. Also you might consider to use std::function<void(const string &)> instead of your function type. This has two fundamental advantages: You can pass closures (also called lambdas) to your constructor and you can read it more easily. The edited code would look like this:
class Foo {
public:
template <typename F>
Foo(string name, F && function)
: m_name (std::move(name))
, m_function(std::forward<F>(function))
{
}
void activate()
{
m_function(m_name);
}
private:
string m_name;
std::function<void(const string &)> m_function;
};
The client code would look like
int main(int argc, char **argv)
{
Foo foo("My foo", [](const string & s){ cout << s << endl; });
foo.activate();
// output: "My foo"
}
You see that the client does not need to define an extra function, but can simply do it 'inline'.
What you're asking is "How can I keep my members private, but still give callbacks some way of accessing them?"
When you look at it that way, your struct FooBar solution is actually pretty reasonable. The only problem is that it's a bit inefficient. You would be better off passing a const FooBar& instead of passing FooBar by value.
Your struct FooBar solution is even better than partial classes, because you can specify exactly which members the callback should have access to.
Edit: Reading your struct FooBar solution more closely, I see you're thinking of tediously copying the members individually before passing them to the callback. You can skip all that just by putting a FooBar object in your Foo class, like so:
struct FooBar {
string name;
};
typedef void(*fptr)(const FooBar&);
class Foo {
public:
Foo(string name, fptr function);
void activate()
{
m_function(data);
}
private:
FooBar data;
fptr m_function;
};
It's worth pointing out that, with this solution, the callbacks cannot access m_function, unless you decide to put it in FooBar. This is what I meant when I said that you can specify exactly which members the callback should have access to.
Let's face it, C++ access control was designed with some use cases in mind, and are generally usable, but never claimed to cover everything. If you can't solve the situation with just private and friend, and arbitrary functions must be allowed to access the internals, then best way is to make them public and move on.
Setters will not move you forward for sure, just add complexity for nothing. If data is effective public don't try to mask that fact pretending like it wasn't.
Look for the root cause -- why on earth outsides want your members and rearrange that.
I could just ignore encapsulation and create a setter and getter for name and all other properties that might be needed by the function in the future. This is pretty terrible solution, I should basically create setter and getter for everything there is in my class, since the function can do anything to my object.
True - this is basically making implementation details public (and in most cases, not something you should do).
An other solution would be a struct that holds the required properties inside it:
[...] But this is not much different from not using encapsulation, and it doesn't seem like a too good solution either. What would be the best approach for this problem?
Actually it is very different. Consider that you are actually calling an external function with normal parameters:
struct EventData { string name, yadayada; }
class Foo
{
public:
void activate()
{
m_function( EventData(m_name, yadayada) );
}
};
This is not accessing private data (Foo accesses it's own private data, m_function accesses it's own parameter values), but dependency injection.
There are no architecture compromises with this approach.
This question already has answers here:
When do I use a dot, arrow, or double colon to refer to members of a class in C++?
(4 answers)
Closed 8 years ago.
Apologies for a question that I assume is extremely basic.
I am having trouble finding out online the difference between the operator :: and . in C++
I have a few years experience with C# and Java, and am familiar with the concept of using . operator for member access.
Could anyone explain when these would be used and what the difference is?
Thanks for your time
The difference is the first is the scope resolution operator and the second is a member access syntax.
So, :: (scope resolution) can be used to access something further in a namespace like a nested class, or to access a static function. The . period operator will simply access any visible member of the class instance you're using it on.
Some examples:
class A {
public:
class B { };
static void foo() {}
void bar() {}
};
//Create instance of nested class B.
A::B myB;
//Call normal function on instance of A.
A a;
a.bar();
//Call the static function on the class (rather than on an instance of the class).
A::foo();
Note that a static function or data member is one that belongs to the class itself, whether or not you have created any instances of that class. So, if I had a static variable in my class, and crated a thousand instances of that class, there's only 1 instance of that static variable still. There would be 1000 instances of any other member that wasn't static though, one per instance of the class.
One more interesting option for when you come to it :) You'll also see:
//Create a pointer to a dynamically allocated A.
A* a = new A();
//Invoke/call bar through the pointer.
a->bar();
//Free the memory!!!
delete a;
Dynamic memory can be a little more confusing if you haven't learned it yet, so I won't go into details. Just wanted you to know that you can access members with { :: or . or -> } :)
in C++ :: is the scope resolution operator. It is used to distinguish namespaces, and static methods, basically any case you don't have an object. Where . is used to access things inside an object.
C# uses the . operator for both of them.
namespace Foo
{
public class Bar
{
public void Method()
{
}
public static void Instance()
{
}
}
}
in C# you would write code like this:
var blah = new Foo.Bar();
blah.Method();
but the equivalent C++ code would look more like this:
Foo::Bar blah;
blah.Method();
But note that the static method would also be accessed using the scope resolution operator, because you're not referencing an object.
Foo::Bar::Instance();
Where again, the C# code would only use the dot operator
Foo.Bar.Instance();
:: is for namespaces and static member access. C# uses the dot-operator for namespaces instead.
. is for non-static member access.
Not an exhaustive delineation, but it's the relevant bits that may confuse you in light of C# and Java.
For further information, see
IBM - Scope Resolution Operator
IBM - Dot Operator
:: is the scope resolution operator, so when you are resolving a scope, such as a namespace or class, you use that. For member access, you have .
The scope operator :: may be hard to understand if you don't understand namespaces or classes. A namespace is like a container for the names of various things in your code. They're generally used to disambiguate names that are common across libraries. Say both namespaces std and example have the function foobar(). So the compiler knows which function you want to use, you prepend it as either std::foobar() or example::foobar().
The :: operator can also be used when telling the compiler you want to define a function declared in a class or structure. For instance:
class foobar()
{
public:
void hello();
int number; //assume there is a constructor that sets this to 5
}
void foobar::hello()
{
cout << "Hello, world!" << endl;
}
The . operator is used when you wish to use a member of a class or structure. For instance:
foobar foo;
foo.hello();
cout << foo.number << endl;
Assuming the class is completed by writing a constructor, the output of this would be expected to be:
Hello, world!
5
You use the . operator the same in java, when accessing members of a class once its created in the program.
the :: is used in number of cases:
When you define a method in the .h/.cpp of a certain class, write
class::methodName()
either for prototyping it, or implementing it.
Also, if you don't explicitly state what namespace you use, you'd have to to use it
std::cout << "This is the output";
instead of just using cout << "This is the output;
Maybe there are more, but i don't remember right now, my C++ is a bit rusty.
In C++, :: is for identifying scope. This can mean namespace scope or class scope.
Eg.
int x;
namespace N {
int x;
struct foo {
static double x;
double y;
};
struct bar: public foo {
double y;
};
}
int main()
{
int x; // we have a local, hiding the global name
x = ::x; // explicitly identify the x in global scope
x += N::x; // explicitly identify the x in namespace N
N::foo::x = x; // set the static member of foo to our local integer
N::foo f;
f.y = f.x; // the static member is implicitly scoped by the object
f.y += N::foo::x; // or explicitly scoped
N::bar b;
assert(b.x == N::foo::x); // this static member is inherited
b.y = b.x; // we get N::bar::y by default
b.N::foo::y = b.y; // explicitly request the hidden inherited one
}
// we need to define the storage for that static somewhere too ...
int N::foo::x (0.0);