How to call static function

Dear experts,

I am coming from Java and I am learning C++ currently.

In java you have so called "static methods" than can be called without having a class instance/object, just like this: Classname.staticmethod();

Is there a similar concept in C++?

I have the following code:

StaticInstance.h
1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma once

class StaticInstance {
public:
	StaticInstance();

	int returnValue();
	static int returnValues();

private:
	int value;

};


StaticInstance.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "StaticInstance.h"

StaticInstance::StaticInstance()
{
	value = 10;
}

int StaticInstance::returnValue()
{
	return this->value;
}

int StaticInstance::returnValues()
{
	int value = 8;
	return value;
}


StaticInstanceMain.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "StaticInstance.h"

int main()
{
	StaticInstance si;

	int v = si.returnValue();
	int a = si.returnValues(); // why can I do this??
	//only StaticInstance::returnValues(); should be correct
	std::cout << v << std::endl;
	std::cout << a << std::endl;
}



In StaticInstanceMain.cpp I am calling the static method "returnValues()" on an
instance. From my understanding this should not be possible, I should only be allowed
to call it like this: StaticInstance::returnValues();

Can you please explain - thank you,
Peter
It's okay to access static members in that way. It's the equivalent of using the :: notation.

https://en.cppreference.com/w/cpp/language/static
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct X
{
    static void f(); // declaration
    static int n;    // declaration
};
 
X g() { return X(); } // some function returning X
 
void f()
{
    X::f();  // X::f is a qualified name of static member function
    g().f(); // g().f is member access expression referring to a static member function
}
 
int X::n = 7; // definition
 
void X::f() // definition 
{ 
    n = 1; // X::n is accessible as just n in this scope
}
Last edited on
However, I want to say that C++ doesn't restrict you to having to use classes, like Java and C# do.

Instead of doing this overengineered class that either returns a 10 or an 8, you could just have a function.

1
2
3
4
int getSpecialValue()
{
    return 8;
}


put it in a namespace if you wish
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace my_namespace {

int getSpecialValue()
{
    return 8;
}

}

int main()
{
    int v = my_namespace::getSpecialValue();
}



Or even:
1
2
3
4
5
6
7
8
namespace my_constants {
    const int SpecialValue = 8;
}

int main()
{
    int v = my_constants::SpecialValue;
}


PS: I'm no expert, but just throwing out some ideas/alternatives.
Last edited on
don't use something other than a constant for a constant in c++.
use constexpr or enums for most constants. Either can be (should be for large code) inside a namespace.

also, static may not (probably does not) mean the same thing in c++. Use it wisely, study it first, it is powerful but like anything powerful, it can also cause trouble if misused.
I strongly suggest taking a bit of time to read - or at least skim - A Tour of C++ by Bjarne Stroustrup (c. 190 pages) from the links on this page:
https://isocpp.org/tour
You don't need to buy it: the drafts will be just fine.

In general, Java is quite similar to C++, but it has a fundamentally different design philosophy: if you try to think in Java while writing C++, you'll have a bad time.

The book I've linked briefly explains what the language can do and when and why to use those facilities. If you have any amount of code to write, reading it would pay off quickly.
Last edited on
Thank you for your helpful answers:
I did not know that both ways are possible:
1
2
    X::f();  // X::f is a qualified name of static member function
    g().f(); // g().f is member access expression referring to a static member function 


Yes, I am still thinking in Java when writing C++ - not a good idea.
And yes, I did not think about "constants" - I am still learning. Just like I am still working on pointers
(which do not exist in Java).
Thank you also for the link https://isocpp.org/tour - I will check it out.

I will have to start thinking in C++ instead of Java - it makes sense.

Best regards,
Peter
which do not exist in Java
Actually they do exists. The keyword new does the same in C++/Java/C#: Create a new instance, calling the constructor, and assigning the pointer. Just because you always use '.' doesn't mean it is not a pointer...

Thus in java/c# it is a good idea to check for null[ptr].
Just like I am still working on pointers
(which do not exist in Java).

I might confuse you more by saying this, but actually in Java you can think of everything except primitive types as being a pointer. It just doesn't use C++ pointer syntax/arithmetic.

For example, consider this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.*;
import java.lang.*;
import java.io.*;
 
class MyClass
{
	public int number;
	public MyClass()
	{
		number = 3;
	}
 
	public static void myMethod(MyClass obj)
	{
		MyClass otherObj = new MyClass();
		otherObj.number = 4;
		obj = otherObj;
	}
	public static void main(String[] args) throws java.lang.Exception
	{
		MyClass obj = new MyClass();
		myMethod(obj);
 
		// What will this print?
		System.out.println(obj.number);
	}
}

Despite the fact that you re-assigned obj in myMethod, the value printed in main will still be 3.
This is because the "handle" itself for the MyClass object is copied to the method, just like a pointer.

Similarly, in C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

void myMethod(int* num_ptr)
{
	int other_data = 4;
	int* other_ptr = &other_data;
	num_ptr = other_ptr;
}

int main() {
	int data = 3;
	int* data_ptr = &data;
	
	myMethod(data_ptr);
	
	// What will this print?
	std::cout << *data_ptr << std::endl;
	
	return 0;
}


We re-assigned a pointer in a function, but that is still just a local variable itself that we're assigning. The value printed in main is still 3, because it hasn't been modified.

...if this confuses you more, please ignore me. I just wanted to point that out.
Last edited on
Hello coder777, Hello Ganado,

Thank you again for your hints. I never looked at Java this way, related to the pointer-logic. You opened my eyes.

Thank you - I have some stuff to think about now...

Best regards, Peter
Topic archived. No new replies allowed.