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:
> Sunday, 26 March 2006 13:45 samaye Steve Graegert alekhiit:
>
> > Please note that static member functions can only access global data
> > or static class data and can not be declared virtual.
>
> So if I want some globally accessible function that is not limited to
> accessing global or static data what should I do?

If you are in a situation like that, you either have poorly designed
the application or you have not fully understood the nature of the
product you're using.

Anyway, if you desperately need this functionality you may want to
write an appropriate accessor method that instantiates the class in
question and returns the non-static member from within a static
context:

--- BEGIN ---
#include <iostream>

using namespace std;

class D {
private:
    int num;
public:
	D() { num = 3; }
	int get_num() {
		return num;
	}
};

class C {
public:
	static int get_num() {
		D *d = new D;
		return d->get_num();
	}
};

int main(void) {
	cout << "C::get_num(): " << C::get_num() << endl;
	return 0;
}
--- END ---

The example prints 3 on stdout.

	\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