Must class constructor variables be assigned to private class variables or is there a less code intensive way? - freepascal

When creating a class you have to assign its parameters to private class variables in order to use those private variables in other procedures and functions in the class. This is code intensive since you have to define the same variable twice.
I have tried using a constructor parameter in a procedure of the same class but it did not work without having to
type
WorldObject=class
private
privX, privY, privStartSpriteNum, privEndSpriteNum:word;
privDirection, privTurn:byte;
public
constructor create(x, y, startSpriteNum, endSpriteNum:word; direction, turn:byte);
procedure draw;
constructor WorldObject.create(x, y, startSpriteNum, endSpriteNum:word; direction, turn:byte);
begin
privX:=x;
privY:=y;
privStartSpriteNum:=startSpriteNum;
privEndSpriteNum:=endSpriteNum;
privDirection:=direction;
privTurn:=turn;
end;
procedure WorldObject.draw;
begin
writeLn(privX);
writeLn(WorldObject.x);
end;
Was expecting writeLn(WorldObject.x) to print the value of x.
But got the error: Identifier idents no member "x".
Is there not a way to use the parameter variables from the constructor without having to pass them to private variables?
Thanks!

You seem to be hoping that there is a mechanism where parameters to constructors are automatically stored somewhere, for retrieval later. There is no such mechanism. It is your responsibility to store any state that you need to refer to outside the scope of your constructor. Using fields of your class is the classic method to do this.

You can write properties instead of copying private variables, you just need to specify where to read and where to write, since then you can use properties in nested classes or even outside the class.
If you need to use them in the nested classes, declare as protected, if not - as public.
property MyProp: TYPE read WriteMyProp read GetMyProp; // for procedure to write and function to read;
property MyPropV: TYPE read MyPropValue write MyPropValue; // for deriving from variable;

Related

AS3: inline way to write get and set?

I was reading a tutorial and the user there was starting setters and getters like so
function get f():Number;
function set f(value:Number):void;
inside an interface, then saving it in the main file inside a variable
var testNode:INode;
and referencing them as
testNode.f;
I thought this was really handy, specially for when you have a lot of variables. Instead of having to create two functions for each private value.
However, I tried to do the same without instancing the get and set inside an interface (because I had no need for this) and I get an error saying the function doesn't have a body.
Why is that? Is there any way to write get and set in such a clean, short manner? So far I've been writing these as
public function get someVar():SomeClass {
return _someVar;
}
public function set someVar(newValue:SomeClass):void {
_someVar = newValue;
}
but it's a bit of a hassle when I have several private variables.
An interface is just a model for your class, it does not allows you to skip the definition of a function (or a getter/setter). You must declare the getter and the setter in any class implementing your interface. What you are looking for is an extension (inheritage).
If you define a class Mother.as with a getter and a setter, the class Child.as which extends Mother.as doesn't need to redefine the getter and setter.
Furthermore, if you don't plan on writing anything else inside the getter and setter, you should use a public variable. These are less resource consuming than useless get/set.

AS3 constructor has no method with the same name as the class

I was reading ActionScript 3.0 Abstract Factory Design Pattern: Multiple Products and Factories, and I have the following,
private var busFactory:AbFactory;
busFactory=new BusinessFactory();
Both in BusinessFactory.as and in AbFactory.as there is no method with the same name as the class, only createProductA and createProductB. So, how could busFactory call the constructor with new BusinessFactory ?
The default constructors for both AbFactory and BusinessFactory (which the article shows inherits from AbFactory) are created by the compiler.
If you start to pass arguments to the BusinessFactory() constructor, the compiler will complain about an unexpected argument count. That's when you need to write the constructor yourself. But passing nothing means the default can be used.
Also the reason that you could set a AbFactory to a BusinessFactory means that they share the same heritage.

Why do constructors not return values?

Please tell me why the constructor does not return any value. I want a perfect technical reason to explain to my students why the constructor does not have any return type.
What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap.
This space includes all members variables and the vtbl. After this space is allocated, the constructor is called as an internal part of the instantiation and initialization process to initialize the contents of the fields.
Then, when the constructor exits, the runtime returns the newly-created instance. So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime.
Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.
Well, in a way it returns the instance that has just been constructed.
You even call it like this, for example is Java
Object o = new Something();
which looks just like calling a "regular" method with a return value
Object o = someMethod();
How is a constructor supposed to return a return value? The new operator returns the newly created instance. You do not call a ctor, newdoes it.
MyClass instance = new MyClass();
If the ctor would return a value, like so:
public int MyClass()
{
return 42;
}
Where would you receive the integer?
(I'm biased towards C++, so regarding other languages, take this with a grain of salt.)
Short answer: You don't want to have to explicitly check for success for every single object construction in your code.
Somewhat longer answer: In C++, constructors are called for dynamically as well as for globally and automatically allocated objects. In this code
void f()
{
std::string s;
}
there is no way for the constructor of s (std::string::string()) to return any value. Either it succeeds - then we can use the object, or it throws an exception - the we never get a chance to try to use it.
IMO, that's the way it should be.
A constructor is some method automatically called when you initialize a new instance of an object.
This method is there if you need to initialize your object to a given state and run few default methods.
Actually you can imagine the constructor always return the instance of the object created that would be a good image.
When you call a constructor the return value is the new object:
Point pt = new Point(1,2);
But within the constructor itself, you're not actually creating and returning the object; it's been created before your code starts, you're just setting up the initial values.
Point::Point(int x, int y) {
this->x = x;
this->y = y;
}
The lack of a return type reflects the fact that constructors are used differently than other functions. A return type of null, while technically accurate, doesn't reflect well the fact that the code is used as if it returns an object. However, any other return type would indicate that your code is supposed to return something at the end, which is also incorrect.
Constructor doesn’t return anything not even Void. Though some of the answers have mentioned that Constructor do return reference to the newly created object , which is not true. It’s the new operator that returns the object.
So Why constructor doesn’t return any value
Because its not supposed to return anything. The whole purpose of constructor is to initialize the current state of the object by setting the initial values.
So Why doesn’t it even return Void
This is actually a Design constraint which has been placed to distinguish it from methods. public void className() is perfectly legal in java but it denotes a method and not a constructor. To make the compiler understand that it’s a constructor , it requires a way to distinguish it.
all answers are biased towards C++/Java. there is no reason a constructor does not return a value other than the language design.
look at a constructor in a broader sense: it is a function which constructs a new object. you can write perfectly valid constructors in C:
typedef struct object object;
int object_create( object **this );
this is perfect OOP in C and the constructor returns value (this can also be called a factory, but the name depends on the intention).
however, in order to create an object automatically (to satisfy some type cast, or conversion for example), there have to be some rules defined. in C++, there is an argument-less constructor, which is inferred by the compiler if it is not defined.
the discussion is broader than what we think. Object Oriented Programming is a name which describes a way of thinking about programming. you can have OO in almost any language: all you need is structures and functions. mainstream languages like C++ and Java are so common that we think they define "the way". now look at the OO model in Ada: it is far from the model of C++ but is still OO. i am sure languages like Lisp have some other ways of doing OO.
One point that hasn't yet been discussed is that the constructor of class "foo" must be usable not only when creating instances of foo, but also when creating instances of classes derived from foo. In the absence of generics (which weren't available when Java, C++, or .net were designed) there would be no way for foo's constructor to return an object of any derived class. Therefore, what needs to happen is for the derived-class object to be created via some other means and then made available to foo's constructor (which will then be able to use the object in question as a foo when doing its initialization).
Even though the VM implementation of a constructor isn't to return any value, in practice it kind of does - the new object's reference. It would then be syntactically weird and / or confusing to be able to store one or both of the new object's reference and an additional return value in one statement.
So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.
Constructor is not directly called by the user's code. It's called by the memory allocation and object initialization code in the run time. Its value is not visible to the user.
In case of C#, the syntax for declaring object is :
classname objectname= new constructor();
According to this line, if we are using assignment operator(=) then it should return some value. But the main objective of a constructor is to assign values to variables, so when we use a new keyword it creates instance of that class, and constructor assigns values to the variable for that particular instance of object, so constructor returns assigned values for that objects's instance.
We can not call constructors independently. Instead they are automatically called whenever objects are created.
Ex:
MyDate md = new Mydate(22,12,2012);
In above example new will return a memory location which will be held by md, and programatically we can not return multiple values in single statements.
So constructors can not return anything.
From what I know about OO design methodologies, I would say the following:
1)By allowing a constructor to return a value, framework developer would allow the program to crash in an instant where the returned value is not handled. To keep the integrity of the program workflow, not allowing a return value from the initialization of an object is a valid decision. Instead, language designer would suggest/force the coders to use getter/setter - access methods.
2)Allowing the object to return a value on initialization also opens possible information leaks. Specially when there are multiple layer or access modifications applied to the variables/methods.
As you aware that when object is created constructor will be automatically called So now imagine that constructor is returning an int value. So code should like this...
Class ABC
{
int i;
public:
int ABC()
{
i=0;
return i;
}
.......
};
int main()
{
int k= ABC abc; //constructor is called so we have to store the value return by it
....
}
But as you aware that stament like int k= ABC abc; is not possible in any programming language. Hope you can understand.
i found it helpful
This confusion arises from the assumption that constructors are just like any other functions/methods defined by the class. NO, they are not.
Constructors are just part of the process of object creation. They are not called like other member functions.
I would be using Java as my language in the answer.
class SayHelloOnCreation {
public SayHelloOnCreation() {
System.out.println("Hello, Thanks For Creating me!");
}
}
class Test {
public static void main(String[]args) {
SayHelloOnCreation thing = new SayHelloOnCreation(); //This line here, produces an output - Hello, Thanks For Creating me!
}
}
Now let us see what is happening here. in java, we use the new keyword to create an instance of a class. And as you can see in the code, in the line, SayHelloOnCreation thing = new SayHelloOnCreation();, the expression after the assignment operator runs before assignment is done. So using the keyword new, we call the constructor of that class (SayHelloOnCreation()) and this constructor creates an object on the Java Heap. After the object is created, a reference to that object is assigned to the thing reference of type SayHelloOnCreation.
The point that I am trying to keep here is that if constructors were allowed to have a return type, Firstly the strongly typed nature of the language would be compromised (Remember I am speaking about Java here).
Secondly, an object of class SayHelloOnCreation is created here so by default I guess the constructor returns a reference of the same type, to avoid ClassCastException.
A method returns the value to its caller method, when called explicitly. Since, a constructor is not called explicitly, who will it return the value to. The sole purpose of a constructor is to initialize the member variables of a class.

What is the advantage of having this/self pointer mandatory explicit?

What is the advantage of having this/self/me pointer mandatory explicit?
According to OOP theory a method is supposed to operate mainly (only?) on member variables and method's arguments. Following this, it should be easier to refer to member variables than to external (from the object's side of view) variables... Explicit this makes it more verbose thus harder to refer to member variables than to external ones. This seems counter intuitive to me.
In addition to member variables and method parameters you also have local variables. One of the most important things about the object is its internal state. Explicit member variable dereferencing makes it very clear where you are referencing that state and where you are modifying that state.
For instance, if you have code like:
someMethod(some, parameters) {
... a segment of code
foo = 42;
... another segment of code
}
when quickly browsing through it, you have to have a mental model of the variables defined in the preceding segment to know if it's just a temporary variable or does it mutate the objects state. Whereas this.foo = 42 makes it obvious that the objects state is mutated. And if explicit dereferencing is exclusively used, you can be sure that the variable is temporary in the opposite case.
Shorter, well factored methods make it a bit less important, but still, long term understandability trumps a little convenience while writing the code.
You need it to pass the pointer/reference to the current object elsewhere or to protect against self-assignment in an assignment operator.
What if the arguments to a method have the same name as the member variables? Then you can use this.x = x for example. Where this.x is the member variable and x is the method argument.
That's just one (trivial) example.
I generally use this (in C++) only when I am writing the assignment operator or the copy constructor as it helps in clearly identifying the variables. Other place where I can think of using it is if your function parameter variable names are same as your member variable names or I want to kill my object using delete this.
Eg would be where member names are same as those passed to method
public void SetScreenTemplate(long screenTemplateID, string screenTemplateName, bool isDefault)
{
this.screenTemplateID = screenTemplateID;
this.screenTemplateName = screenTemplateName;
this.isDefault = isDefault;
}

public and private modifiers for variables in access form module

I have a form module in my access project. In the top of the module, I declare a variable like so:
option explicit
private id_foo as long
I want to explicitely state that I need the variable in my form module by using the private access modifier on it.
Now, further down in the same form module, I have a function that needs to know and/or modify the value of id_foo:
function bar() as long
call do_something(me.id_foo)
end function
Yet, this doesn't work. But when I change the private modifier to a public modifer like
public id_foo as long
it does work.
This behaviour strikes me as odd or unintuitive, and, in fact, I can't see the meaning of public and private if I have to declare the variable as public anyway in order to use it in the same form module.
So, am I overlooking something obvious or is this how it is supposed to be?
Thanks / Rene
Try it without the "me" in front of id_foo:
function bar() as long
call do_something(id_foo)
end function
If you use the me keyword, you can see only public members, properties (also Form and VBA).
A form along with its module actually represents a class object. You can also create (instanciate) multiple Instances of that class object.
So, Any variable you declare as public becomes a public property of that class object. Note that any function in the forms code module declared as public becomes a public method of that class object. All of these properties and methods then show up in the intel-sense when you type in the "me." keyword.
If you declare the variable as private, then that variable (or function) will not be exposed as a public property (variable) or a public method (function) of the form.
So the simple solution your cases is to drop the use of the me keyword in your code, and it you code will run just fine at.
So declaring as public or private does have an effect here. In fact, “private” is the default.
So, public will expose the variable and/or functions as properties and methods of that form which is a class object (note that you can have Multiple instances of the same form loaded at the same time).
If you decleare things as private (the default, so you don’t have to do anything for the Variable or function) then you can still use the value in ANY code routine in that forms code module, but it will not be public exposed as a property/method and thus you can't use me.
Thus, your code will work fine if you remove the use of the me., and just go:
function bar() as long
call do_something(id_foo)
end function