CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2009
    Posts
    6

    Static Functions

    Hi, I was wondering how to reference non static variables from within a static function. Do you have to recast them as static within the function? I'm completely new at static programming, so if anyone has any good tutorials it would be much appreciated.

  2. #2
    Join Date
    Feb 2009
    Location
    India
    Posts
    444

    Re: Static Functions

    You cannot.
    The reason originates at what happens when a class is instantiated.

    When a class is instantiated, memory is allocated for the non-static data members.
    That means when a class is not instantiated, no memory is allocated for the non-static data members and hence they cannot be accessed.

    A non-static method can access non-static data members.
    So non-static methods can only be called after a class is instantiated.

    Now static methods can be called without instantiating the class.
    So if a static method calls a non-static method which in turn accesses non-static data members and the class is not instantiated, you're trying to access invalid memory.
    «_Superman
    I love work. It gives me something to do between weekends.

    Microsoft MVP (Visual C++)

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Static Functions

    You'll have to pass a pointer to the particular object you want to access into the method.

    Let's say you have a class called Car, with a non-static member "color" and a static method "carsSoldAtDealership()". The latter is clearly not meant to apply to any particular Car object; it simply related to them, and is thus included in the class. If you tried to access the "color" field within carsSoldAtDealership(), which Car are you interested in the color of? It doesn't make sense to ask the question.

    If you also had a static method "computeTimeOfNextService(Car *c)", then you could pass a pointer to a Car into the method and it would then be able to access that Car's private fields since it's a class member. Of course, you could equivalently make this a non-static method taking no parameters, so that which Car it is operating on is implicit.
    Last edited by Lindley; July 2nd, 2009 at 01:00 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured