I'm pretty new to OO and have a simple question. Can you create a class such that each new object created from it has an initial state defined by a function? Only way I've been able to get it to work is by first creating the object, then calling a method on the object to set it's state via the function (see below). If I try to bring up the function to set it's state into the initiator code it doesn't work right (each time it is called it resets the state of all objects I've created). Can somebody help me understand this???
classA = oo.class()
function classA:__init()
self.a_number = 0
return oo.rawnew(self)
end
function classA:set_number()
self.a_number = io.read("*number")
end
x = classA()
x:set_number()
y = classA()
y:set_number()
Quick newbie question on instantiating object classes with variable initial state
Started by theedrock, Jun 20 2010 04:28 PM
2 replies to this topic
#1
Posted 20 June 2010 - 04:28 PM
|
|
|
#2
Posted 20 June 2010 - 06:21 PM
Never mind. I figured it out as I was doing the init return call wrong apparently. The following code seems to work as I wanted:
classA = oo.class()
function classA:__init()
local temp = io.read("*number")
return oo.rawnew(self,{a_number = temp})
end
x = classA()
y = classA()
classA = oo.class()
function classA:__init()
local temp = io.read("*number")
return oo.rawnew(self,{a_number = temp})
end
x = classA()
y = classA()
#3
Posted 20 June 2010 - 11:33 PM
theedrock said:
Can you create a class such that each new object created from it has an initial state defined by a function?
In C++ and other programming languages, there's a special method called the constructor.
For example:
#include "SomeHeaders.h"
class foo
{
private:
int nNumber;
public:
foo(int nNumber)
{
this->nNumber = nNumber;
}
};
int main()
{
foo *ptrfoo = new foo(3); //This instance's nNumber is set to 3
//...
delete ptrfoo;
ptrfoo = NULL;
return 0;
}
The constructor is called in the first line of main.
Greets,
artificial
Edited by artificial, 21 June 2010 - 01:36 AM.


Sign In
Create Account

Back to top









