linux-c-programming.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: "Steve Graegert" <graegerts@gmail.com>
To: linux-c-programming@vger.kernel.org
Subject: Re: Accessing a class' member functions
Date: Sun, 26 Mar 2006 08:15:58 +0000	[thread overview]
Message-ID: <6a00c8d50603260015ud777b7fgfbfa02f567cf8b@mail.gmail.com> (raw)
In-Reply-To: <200603260931.05639.samjnaa@gmail.com>

On 3/26/06, Shriramana Sharma <samjnaa@gmail.com> wrote:
> I need to use a class' member functions without creating an instance of that
> class. Is that possible? I have seen someone do this in their C++ library but
> it does not work for me, so I am wondering what I did wrong.

What you've have seen are static member functions.  They can be called
withouth creating an instance of the class they are defined in.

Please note that static member functions can only access global data
or static class data and can not be declared virtual.  Since stattic
member functions exist without class instances, you cannot use the
implicit this pointer to access non-static members.

To access static members you simply use the class name and append the
member using the scope operator: MyClass::myStaticMember.

Example:

-- BEGIN ---
#include <iostream>
#include <cstdlib>
#include <ctime.h>

class C {
private:
    static const int MAX_NUM = 10;
public:

    static void get_num () {
        srand((unsigned)time(NULL));
        return (int)(MAX_NUM * rand() / (RAND_MAX + 1.0));
    }
};

int main(void) {
    cout << C::get_num() << "\n";
}

--- END ---

	\Steve

  reply	other threads:[~2006-03-26  8:15 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2006-03-26  4:01 Accessing a class' member functions Shriramana Sharma
2006-03-26  8:15 ` Steve Graegert [this message]
2006-03-26 12:39   ` Shriramana Sharma
2006-03-26 14:46     ` Steve Graegert
2006-03-26 16:09     ` Glynn Clements

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=6a00c8d50603260015ud777b7fgfbfa02f567cf8b@mail.gmail.com \
    --to=graegerts@gmail.com \
    --cc=linux-c-programming@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).