Re: Accessing a class' member functions

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 3/26/06, Shriramana Sharma <samjnaa@xxxxxxxxx> 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
-
: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux