c static method calls with friendly method name - c++

I have a header file helper.h
class helper
{
public:
static int someVal();
};
int helper::someVal()
{
return 999;
}
In my c class I call the someVal method as follows
#include "helper.h"
.
.
int answer = helper::someVal();
Is there way to have a call like this instead?
int answer = someVal();
Solution from below is
helper.h --
static int someVal();
int someVal()
{
return 999;
}

Not exactly, but you can make helper a namespace instead of a class:
namespace helper
{
static int someVal();
}
using namespace helper;
int answer = someVal();
You can define the function just as you did in the question. In practice is's often better to not use using namespace for your own functions because that makes it easier to understand which function is called.

If you only have a class with static functions, you could use a namespace with functions instead. You could later use using namespace to access the function without the namespace name.

why should you want to? someone reading the code (even yourself in near future) is very happ not to misinterpret the function as global. when you do good naming on class and member function you would miss important information without class name. Factory::get_instance() carries more information than get_instance().

Related

Why I can't use my class without parenthesis?(in C++)

//this is main.cpp
#include <iostream>
#include "Cook.hpp"
using namespace std;
int main(void){
int l = Cook.get_life();
}
//this is cook.hpp
#ifndef HUNTER_H
#define HUNTER_H
class Cook
{
public:
int get_life(void);
private:
int life;
};
#endif
//this is cook.cpp
#include "Cook.hpp"
int Cook::get_life(void)
{
life=0;
return life;
}
They are all in same folder. And I get compile error when I run main.cpp. And Xcode recommended to use Cook().get_life() instead of Cook.get_life(). Can you explain why? I thought I should use Cook.get_life.
I use Xcode.
First you have to declare variable with type of you class (instance) and then you can use it, But classes has static functions too, that mean you can use function without declare instance of it first but in that you can't use member variable of class, Reading more about concept of classes and more ...
get_life is not a static function, you have to call it on an instance of your class Cook, and that's exactly what Cook() does. If you want to call get_life without an instance of Cook, you should declare your function this way :
static int get_life(void);
And then call it like that :
Cook::get_life();
The thing is you can't use class attributes from static member functions, so instead you need to instantiate your class Cook before calling your member function.
Cook c = Cook(); // Cook().get_life() works to, but you don't keep your newly created object
c.get_life();

Using namespace for static class members

Can someone explain why the following code does not work? I cannot find any resources explaining the how namespaces, classes and identifiers fit together. When you do my_class::my_member, the my_class:: part is not a namespace? What is it?
#include <iostream>
class my_class {
public:
static void my_member() {
std::cout << "worked" << std::endl;
}
};
int main() {
using namespace my_class; // error: 'my_class' is not a namespace-name
my_member(); // error: 'my_member' was not declared in this scope
my_class::my_member(); // works
}
As a more general question: is there a way I can reference static class members without doing the my_class:: namespace/ identifier/ whatever each time?
Instead of
my_class::my_member_1
my_class::my_member_2
I just want
my_member_1
my_member_2
Is this possible? Thank you.
Is this possible?
Yes, indirectly. If you create a method that operates in my_class's scope, then you can get the behavior you want.
#include <iostream>
class my_class {
public:
static void my_member() {
std::cout << "worked" << std::endl;
}
static int my_main();
};
int my_class::my_main() {
my_member(); // no error
my_class::my_member(); // works too
return EXIT_SUCCESS;
}
int main() {
my_class::my_main();
}
my_class is not a namespace, it is a class name (a type). Therefore, you cannot use using namespace with my_class.
If you want to use my_member_1 without prefixing the class name, create a global wrapper function.
void my_member_1() {
my_class::my_member_1();
}
When you call a static function like this :
my_class::my_member();
You are refering to the class definition to find the static function. A static function will be the same for every instance of your class. You cannot access the static function either by simply calling the function name, or by creating an instance of the class to call the static function.
If you want to call directly the static function without writing down the class definition, you could do something like :
#define my_member_1 my_class::my_member_1()
#define my_member_2 my_class::my_member_2()
...
After that you could simply call my_member_1 to execute your static function, but that could get confusing on a large scale program. My advice is to keep using the class definition so you know exactly what function you are calling.

Creating a C++ namespace in header and source (cpp)

Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace in the cpp file?
By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.
Example:
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
namespace X
{
void Foo::TheFunc()
{
return;
}
}
VS
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
using namespace X;
{
void Foo::TheFunc()
{
return;
}
}
If there is no difference what is the preferred form and why?
The difference in "namespace X" to "using namespace X" is in the first one any new declarations will be under the name space while in the second one it won't.
In your example there are no new declaration - so no difference hence no preferred way.
Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.
The only problem that arises with using namespace is when we have same nested namespace names (i.e) X::X::Foo. Doing that creates more confusion with or without using keyword.
There's no performance penalties, since the resulting could would be the same, but putting your Foo into namespace implicitly introduces ambiguity in case you have Foos in different namespaces. You can get your code fubar, indeed. I'd recommend avoiding using using for this purpose.
And you have a stray { after using namespace ;-)
If you're attempting to use variables from one to the other, then I'd recommend externalizing them, then initializing them in the source file like so:
// [.hh]
namespace example
{
extern int a, b, c;
}
// [.cc]
// Include your header, then init the vars:
namespace example
{
int a, b, c;
}
// Then in the function below, you can init them as what you want:
void reference
{
example::a = 0;
}
If the second one compiles as well, there should be no differences. Namespaces are processed in compile-time and should not affect the runtime actions.
But for design issues, second is horrible. Even if it compiles (not sure), it makes no sense at all.
The Foo::TheFunc() is not in the correct namespacein the VS-case. Use 'void X::Foo::TheFunc() {}' to implement the function in the correct namespace (X).
In case if you do wrap only the .h content you have to write using namespace ... in cpp file otherwise you every time working on the valid namespace. Normally you wrap both .cpp and .h files otherwise you are in risk to use objects from another namespace which may generate a lot of problems.
I think right thing to do here is to use namespace for scoping.
namespace catagory
{
enum status
{
none,
active,
paused
}
};
void func()
{
catagory::status status;
status = category::active;
}
Or you can do the following:
// asdf.h
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
Then
// asdf.cpp
#include "asdf.h"
void X::Foo::TheFunc()
{
return;
}

What is the difference between "using" namespace and declaring namespace?

Could somebody tell me what is the difference between
using namespace android;
....
and
namespace android {
....
}
I found that almost all .cpp files in Android source code use the second one.
Also, If I want to include some files that use the type of second one in my own project, do I need to use namespace android{...} too?
Because if I do not, compiler would report error when I call methods of included files. Or do I need to add any prefix before method call?
namespace android {
extern int i; // declare here but define somewhere
void foo ();
}
-- is used for scoping variables and functions inside a particular name. While using/calling those variables/functions, use scope resolution operator ::. e.g.
int main ()
{
android::foo();
}
There is no restriction for putting all namespace declarations in a single body instance. Multiple namespace android bodies spread across several files, is possible and also recommended sometimes. e.g.
// x.cpp
namespace android {
void somefunc_1 ();
}
// y.cpp
namespace android {
void somefunc_2 ();
}
Now, sometimes you may find using :: operator inconvenient if used frequently, which makes the names unnecessarily longer. At that time using namespace directive can be used.
This using directive can be used in function scope / namespace scope / global scope; But not allowed in class scope: Why "using namespace X;" is not allowed inside class/struct level?).
int main ()
{
using namespace android;
foo(); // ok
}
void bar ()
{
foo(); // error! 'foo' is not visible; must access as 'android::foo()'
}
BTW, Had using namespace android; declared globally (i.e. above main()), then foo() can be accessed without :: in Bar() also.
My answer is probably only helpful if you are more experienced with Java. I'm guessing since you are doing android stuff that this is the case.
The following means that you are declaring a class called MyClass in the namespace android. The qualified name of the class would be android::MyClass.
namespace android {
class MyClass {...};
}
It can be thought of similarly to the Java code:
package android;
public class MyClass {...}
The following means that you can use classes, functions etc. defined in the android namespace without having to use their qualified name (assuming they have been included).
using namespace android;
This
#include <path/to/MyClass.h>
using namespace android;
can be thought of similarly to the Java code:
import android.MyClass;

Accessing variables outside the program in C++

id.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
static int a;
};
int A::a=20;
class b
{
public:
b()
{
cout<<A::a<<endl;
}
};
int main()
{
b *b1 = new b();
return 0;
}
id1.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class c
{
public:
int get()
{
cout<<A::a<<endl;
}
};
int main()
{
c c1;
c1.get();
return 0;
}
This is the way they have declared and got the output in one program but when I'm trying it I'm getting errors as the class is not a namespace or the program id is not included in the id1 file... How to get the variable that is stored in one file into the other file without using namespace and including the header file is there any option for it?
Two separate programs as shown (they're separate because they both define main()) cannot share variables in any simple way.
If the two separate files were to be integrated into a single program, so one of the main() programs was replaced, then you would fall back on the standard techniques of declaring the variable A::a in a header and using that header in both modules. The header would also define class A. This is the only sane way to do it.
You could write the definition of the class twice, once in each file, and declare the variable as an extern in one file and define it in the other, but that is not particularly sensible even in this simple case and rapidly degenerates into unmaintainable disaster if the code gets any more complex and there are more shared variables.
Of course, you might want to consider not using a global variable at all, but provide instead an accessor function. However, you still end up with a header declaring the services provided by the class A and the code implementing those services, and the code consuming those services.