private

Tom Seddon sorry at no.mail.address
Thu Jul 4 17:04:15 EDT 2002


In article <mailman.1025382159.23425.python-list at python.org>, 
dreed at capital.edu says...
> > From: Peter Hansen <peter at engcorp.com>
> > X-Accept-Language: en
> > Newsgroups: comp.lang.python
> > Xref: news.baymountain.net comp.lang.python:170296
> > Sender: python-list-admin at python.org
> > Date: Sat, 29 Jun 2002 12:32:50 -0400
> > 
> > Rhymes wrote:
> > > 
> > > Is there any possibility to build up a _real_ private attribute?
> > 
> > Please define what "_real_" means to you.  It's not apparent.
> > 
> > > Such as C++ private data members...
> > 
> > You realize that it's quite possible to get at private data members
> > in C++, don't you?
> 
> Kind of off-topic, but this got me curious. The only way I could think
> of is to assume (which I think is always true) that the private data
> members are in order from the starting address so based on the offset
> from the address of the object you could access each one.
> 
> Is there another way?
> 
> Dave

You need a class with a member template function. You then specialize 
this outside the class declaration.

#include <iostream>

//tried with intel C++ 5.0

struct K {
public:
	K():j(1) {}
	template<class T>
	void f(T r) {
		j=5;
	}
	int r() {
		return j;
	}
private:
	int j;
};

template<>
void K::f(void *p) {
	j=6;
}

int main(int argc,char *argv[]) {
	K test;
	std::cout<<test.r()<<std::endl;
	test.f(100U);
	std::cout<<test.r()<<std::endl;
	test.f(static_cast<void *>(0));
	std::cout<<test.r()<<std::endl;
	return 0;
}

The program prints 1 then 5 then 6. You have to pretend the class is in 
a library header and the specialization is in my own code.

this was a guru of the week on comp lang c++ a while ago.

-- 
-- 
--Tom
tom under score seddon snail gmx stop co stop uk
(spam paranoia)



More information about the Python-list mailing list