Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
See more:
I know my question may sound stupid but still thought of giving it a try

My question is that we access a static function with the help of a class name and if we access the static function with the help of an object then we get error, why is this so.

I know a static block or function gets memory before the object gets created then why not access the static function via object name after the object creation. I read many books but none have a clear cut explanation for this please help me out

Thanks and Regards
Radix
Posted
Comments
SenAPI 6-Feb-11 11:07am    
in C++ we can call static method with the help of object.

There is a lot of articles with clear explanation, you just need to read properly.

Static function is called just by address of the entry point. An instance function, in contrast, is a function with additional hidden parameter called this, in some languages self. Technically, it is passed exactly as any other parameter, usually first one.

So if you have this:

C#
class MyClass {
   public void MyMethod(int parameter) {/*...*/ someField = parameter; }
   private int someField;
}
MyClass myVariable;
myVariable.MyMethod(3);


Behind the scene it works exactly like this (pseudo-code! not real code!):
C#
MyClass.MyMethod(myVariable, 3);


As myVariable is passed as a parameter, it provide access to the instance members (like someField), same thing about other (non-static methods): they will need this way as well, passed from a calling instance method. That's why you cannot call instance method from static once, without some instance. You can only access other static members (including methods) from static methods.

Naturally, from an instance method you can access all visible members, both static and instance ones.

For a reference, see my other Answer: What is the Extra Advantage of Delegate[^] — it's more on delegates but can be useful.

That should resolve your confusion completely, I hope.

—SA
 
Share this answer
 
v3
Comments
fjdiewornncalwe 1-Feb-11 14:25pm    
OPs answer moved here:
@SAKryukov:

hi, itried this code in java and it works fine with static functions and variables

class Myclass
{
private static int x = 20;
static void foo()
{
System.out.println("I am a static fun");
}

public static void main(String args [])
{
Myclass.foo();
Myclass obj = new Myclass();
obj.foo();
System.out.println("Int val is:"+obj.x);
}
}

As per your explanation i feel that every thing internally is been called via class name, earlier what i thought that since object is created inside the main method and main is static so the object that i have created is also static since everything inside the static block is static and hence i can access the static variable and function.
Espen Harlinn 1-Feb-11 17:44pm    
Nice explanation, a 5+
radix3 2-Feb-11 3:13am    
The above java code is working becoz in java the objects type is checked and then the static method is called, in c++ this is not the case the object's type is not checked.
Hence if you call a static function in java it will work fine but not in c++
Sergey Alexandrovich Kryukov 2-Feb-11 11:27am    
What do you mean type checked and not checked? Possible to call C++ static function with wrong profile? Not way! If you mean something else, please explain.
--SA
It's to do with the language semantics/syntax. Example, with C#, this won't compile:

C#
class A
{
    public static void Foo()
    {
    }
}

static void Main(string[] args)
{
    A a = new A();
    a.Foo();


But the following C++ code will compile, and run:

C++
class A
{
public:
    static void Foo(){}
};

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    A a;
    a.Foo();
 
Share this answer
 
v2
Comments
radix3 1-Feb-11 13:58pm    
but still i wana know why is this that all the books say that dont access static function via object of the class, and thanks for the answer
Nish Nishant 1-Feb-11 14:01pm    
Only C# books would say that. In C++, the generated code is identical whether you call it through the class name or through an instance.

And as for C#, the designers of the language decided that it's best to have it that way. It's less ambiguous that way, and you can quickly differentiate between instance and static methods.
Sergey Alexandrovich Kryukov 1-Feb-11 14:02pm    
Nishant, please read my answer. You cannot explain how it works without explaining the role of "this", don't you agree?
--SA
Nish Nishant 1-Feb-11 14:06pm    
I don't think the OP's confused about that, he seems to know the difference between instance and static methods. He is wondering why C# chose to go in a direction different from C++. In C++, if you write code where you "apparently" call a static method on an instance, the compiler interprets it to be a call on the class. In C# things are more clear, you have to explicitly use the class name, the compiler does not do any re-interpreting for you. I think that's what's confused the OP. His main query is why C# did not do it that way too.
Emilio Garavaglia 1-Feb-11 16:45pm    
Not sure: The OP says "I know a static block or function gets memory before the object gets created ..."
Not a sign of good understanding of the terminology
A class static function is nothing more than an ordinary function. It exist in the class name scope, but doesn't see any class data.

A class member function is a function that have visibility of the data of a class instance.

C#
struct A
{
    int m;
    static bool static_method(int x)
    {
        /* do something not using m */
        // return m==x; //this will be an error.
        return x==0;
    }
    bool method(int x)
    {
        /* do something with m */
        return m==x;
    }
};
void test()
{
    A a1, a2;
    a1.m=1;   a2.m=2;
    verify(a1.method(1)); //succeed
    verify(a2.method(2)); //succeed
    //verify(a1.method(3)); //will fail: 3!=1
    //verify(a2.method(4)); //will fail: 4!=2
    verify(A::static_method(0)); // will call A::static_method ...
    verify(a1.static_method(0)); // ... three time, all without ...
    verify(a2.static_method(0)); // ... access the m member.
    //verify(A::static_method(1)); //will fail: 1!=0
    //verify(a1.static_method(1)); //will fail: 1!=0
}


In C++, a1.static_method is allowed, but it is perfectly identical to A::static_method, and -in any case, will get nothing from the a1 object.
In C# the designer of the language decided not to allow that redundant way to specify the same call.
 
Share this answer
 
Comments
radix3 2-Feb-11 3:15am    
will have to check it out with c++,
"My question is that we access a static function with the help of a class name and if we access the static function with the help of an object then we get error, why is this so" I believe it is so because static applies to all objects of a particular class or just a particular class as a whole, therefore, you access the static function using the class name rather then the instance of the class or an object.

Simple Example:
ClassA a(10);
//a.static_function(); //this is wrong because static is referring to any instance of a class

ClassA.static_function();//this is correct because static is referring to a class or every instance of an object


Note: I could be wrong about this, please someone verify.
robNO.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900