Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Are there official definitions for these terms in OOP?
Or have they just evolved over time and depending on your former computer science education (or even your age) you use one or the other?
So far i found good definitions of method vs. function:
Difference between a method and a function
A function is a piece of code that is called by name.
... All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by name that is associated
with an object.
And function vs. procedure:
What is the difference between a "function" and a "procedure"?
A function returns a value and a procedure just executes commands.
A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of
commands. Hence the difference is only in the returning a value part.
Even if there are subtle differences in the definition by the authors the main aspect seems to be: A method is always something which operates on an object in contrast to a function which gets all data passed to it by its parameters. If a function does not return a value it is called a procedure.
But how are subroutine and especially operation linked to these terms?
EDIT: Since this seems to be too broad here is an attempt to narrow it down: method, procedure and function are pretty clear from my former research. Also subroutine is not that vague anymore.
So the question is: What is an operation in the field of computer science?
The following is my understanding. Note that these are all "soft" definitions - there is no official definition of any of these, and so the exact meaning may vary between languages. (For example, "static methods" in Java and C# don't fit my definition of "method", unless you consider classes to be objects)
A subroutine is "some code that you can call whenever". It's literally a routine that is called by other routines (hence a sub-routine). "Subroutine" and "routine" seem to be quite archaic terms.
Think of BASIC's GOSUB instruction: (never mind that BASIC is a terrible language)
10 PRINT "Hello"
20 GOSUB 100
30 PRINT "Goodbye"
40 GOSUB 100
50 END
100 PRINT "World"
110 RETURN
This prints:
Hello
World
Goodbye
World
In Visual Basic, a subroutine or Sub is a function which doesn't return anything.
A procedure is the same thing as a subroutine, but less archaic.
A procedure can also mean a function which doesn't return anything.
A function is like a procedure, but instead of just being a list of commands, it can take parameters and return a value. You should be familiar with functions from many languages, but here's an example in C++:
#include <iostream>
using namespace std;
int calculate(int a, int b) {
return a + b - 2;
}
int main() {
cout << calculate(5, 2) << endl;
cout << calculate(100, 20) << endl;
int i = calculate(5, 1);
for(int k = 0; k < i; k++) // repeat the next line i times
cout << "Hello" << endl;
}
This prints:
5
118
Hello
Hello
Hello
Hello
Notice that the function calculate doesn't do the printing itself - instead, it returns a number which main can choose to print, or to do something else with. The third call to calculate returns 2, but the 2 isn't printed - instead, it determines how many times "Hello" is printed.
A function with no arguments, that returns nothing, is equivalent to a procedure (or subroutine).
A method is a function which can be called on an object. You might be familiar with non-static methods from Java or C#. A method has access to the state of the object it was called on (which is called the receiver).
Unlike with functions, methods are often polymorphic on the type of the receiver - it's not possible to directly see which sequence of commands will run when you make a method call.
A simple example of methods in Java, demonstrating polymorphism:
class Car {
int getNumberOfWheels() {return 4;}
void printNumberOfWheels() {
System.out.println(getNumberOfWheels());
}
}
class HondaCivic extends Car {
// no code here
}
class ReliantRobin extends Car {
int getNumberOfWheels() {return 3;}
}
class Main {
public static void main(String[] args) {
Car h = new HondaCivic();
Car r = new ReliantRobin();
h.printNumberOfWheels();
r.printNumberOfWheels();
}
}
This prints:
4
3
even though you might think that printNumberOfWheels always prints 4 - subclasses can "intercept" the getNumberOfWheels method call.
Related
I'm working on a custom interpreter for fun ;)
What I have so far is assigning variables, defining and calling functions, arrays, loops, if blocks etc...
I've started adding OOP elements to my language and I'm having trouble implementing the "this" / "self" keyword.
I just cannot figure out a solution to this problem.
I've thought about a few solutions:
a class stores it's instances (as a dictionary) and when the "this" keyword appears, the interpreter ignores "private" and "public" keywords (to call a private method from a public one), creates a call to the method referenced by "this" and returns.
the "this" keyword is a reference which under the hood is the instance itself, but the method access modifiers are dropped for that call. this is similar to the first one, but I cannot think of anything better.
Also it would be nice if you knew C# (primarly) or C++, since I'm heavily relying on OOP to create my interpreter.
heres a small sample of code that I would like to implement:
struct Dog has
pub prop age;
prv def bark() do
println "woof woof";
end
pub def run(dist) do
loop 0 to $dist with "d" do
println ("the dog ran " + string $d) + " meters";
$self.bark();
end
end
end
def main(args) do
new Dog -> $dog;
7 -> $dog.age;
println $dog.age;
$dog.run 30;
end
notice that the bark() method is "prv" (private). I would like to know how can I make the struct be aware of it's instances so I can make the dog bark each time it runs (calling a private method from a public method).
Thanks in advance
Your interpreter is going to need to keep an execution stack and environment (otherwise you wouldn't know where to return to after a method is finished, etc.).
In this execution stack/env, apart from a function pointer/signature, you'd also keep the object the method is being invoked on (if any, remember about static-like functions).
This reference that you'd store would then be also accessed when de-referencing $this. And actually this is both part 1 and 2 of your idea - you could put some kind of checks like visibility of methods etc. there.
Good luck, sounds like a fun project!
Why is the value of 'a' being printed for variable 'b' ?
Acc. to what i understand variable of subroutines are stack-dynamic-variables and memory cells for subroutines are allocated when the subroutine begins execution, and are de-allocated when the subroutine ends execution.(Took this info from - https://cse.buffalo.edu/~shapiro/Courses/CSE305/Notes/notes6.html)
Please tell me if am wrong.
using namespace std;
void a(){
int a = 743;
cout<<a<<endl;
}
void b() {
int b;
cout<<b<<endl;
int main() {
a();
b();
return 0;
}
It's because you're not initialising b in your second function, meaning it will have some arbitrary value. The value that it's getting in this case appears to be the value of a from the previous function.
When you call a function, it adjusts the stack pointer so that it has a stack frame separate from the caller main(). Calling a() does that and it will then set some memory location (for the local variable a) in its stack frame to be 743.
When we then exit a(), we adjust the stack pointers so that we are once again using the stack frame of main() but we do not clear out the memory where the a() stack frame was.
Then, on calling b(), we adjust the stack frame and, given the similarity between the two functions (same number of parameters, same number of local variables, etc), the memory location of b just happens to be where a was when a() was executing.
That's why it has the same value.
Keep in mind this is only due to the particular scenario you have and is in no way guaranteed by the standard. The instant you used b without first initialising it, you were guaranteed to get some arbitrary value.
Bottom line, initialise your variables before you attempt to use them.
First of all: the title of this post does not match the actual question I have.
But I am also supplying the answer to the original problem (NullRefExcp on bool), so other users will find it's solution here by the chosen title.
I have a class, similar to the following:
ref class CTest
{
bool m_bInit;
void func()
{
if (!m_bInit)
return;
...
}
...
}
Today I had the problem that func crashed with a NullReferenceException at some point although it had been executed successfully many times before.
The exception occured in the line if (!m_bInit)!
I know, you all are saying now, that this is impossible. But it actually was this line. The reason was following:
I have two different variables, both named oTest, but at different places. One of them was initialized: oTest = gcnew CTest. Calling func on this oTest worked well. The first call of func on the other oTest failed with the exception from above. The curious thing is, that the crash seems to happen at the query on m_bInit, also the stacktrace of the exception tells so. But this was just the first place where a member of the not initialized object (it was still nullptr) was called.
Therefore, the advice for other users with the same problem: Check the stack backwards to find a function call on an object that is nullptr/null.
My question now is:
Why does the execution not fail on the first call of a function of oTest which is nullptr?
Why is the function entered and executed until the first access to a member?
Actually, in my case 3 functions were entered and a couple of variables were created on the stack and on the heap...
This code:
void func()
{
if (!m_bInit)
return;
...
}
could actually be written as:
void func()
{
if (!this->m_bInit)
return;
...
}
Hopefully now you can see where the problem comes from.
A member function call is just a regular function call that includes the this parameter implicitly (it's passed along with the other parameters).
The C++/CLI compiler won't perform a nullptr check when calling non-virtual functions - it emits a call MSIL opcode.
This is not actually the case in C#, since the C# compiler will emit the callvirt MSIL opcode even for non-virtual functions. This opcode forces the JIT to perform a null check on the target instance. The only ways you could get this error in C# is by calling the function via reflection or by generating your own IL that uses the call opcode.
This question already has answers here:
Difference between . and : in Lua
(3 answers)
Closed 8 years ago.
I'm still playing around with lua modules and I've found the following "interesting" issue that occurs depending on how you create your methods / functions inside a module.
Note the following code in a file called test_suite.lua:
local mtests = {} -- public interface
function mtests:create_widget(arg1)
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
return mtests
Using the above code, arg1 is always nil, no matter what I pass in when calling create_widget(). However, if I change the definition of the function to look like this:
function mtests.create_widget(arg1) -- notice the period instead of colon
print(arg1)
-- does something
assert(condition)
print("TEST PASSED")
end
then, the system displays arg1 properly.
This is how I call the method:
execute_test.lua
local x = require "test_suite"
x.create_widget(widgetname)
Can you tell me what the difference is? I've been reading: http://lua-users.org/wiki/ModuleDefinition
But I haven't come across anything that explains this to me.
Thanks.
All a colon does in a function declaration is add an implicit self argument. It's just a bit of syntactic sugar.
So if you're calling this with (assuming you assign the mtests table to foo), foo.create_widget(bar), then bar is actually assigned to self, and arg1 is left unassigned, and hence nil.
foo = {}
function foo:bar(arg)
print(self)
print(arg)
end
Calling it as foo.bar("Hello") prints this:
Hello
nil
However, calling it as foo:bar("Hello") or foo.bar(foo, "Hello") gives you this:
table: 0xDEADBEEF (some hex identifier)
Hello
It's basically the difference between static and member methods in a language like Java, C#, C++, etc.
Using : is more or less like using a this or self reference, and your object (table) does not have a arg1 defined on it (as something like a member). On the other way, using . is just like defining a function or method that is part of the table (maybe a static view if you wish) and then it uses the arg1 that was defined on it.
. defines a static method / member, a static lib, Which means you can't create a new object of it. static methods / libs are just for having some customized functions like printing or download files from the web, clearing memory and...
: Is used for object members, members that are not static. These members change something in an object, for example clearing a specified textbox, deleting an object and...
Metamethod functions(Functions that have :) can be made in lua tables or C/C++ Bindings. a metamethod function is equal to something like this on a non-static object:
function meta:Print()
self:Remove()
end
function meta.Print(self)
self:Remove()
end
Also, with . you can get a number/value that doesn't require any call from a non-static or static object. For example:
-- C:
int a = 0;
-- Lua:
print(ent.a)
-- C:
int a()
{
return 0;
}
-- Lua:
print(ent:a())
same function on a static member would be:
print(entlib.a())
Basically, each non-static object that has a function that can be called will be converted to : for better use.
Is it possible to call a function by name in Objective C? For instance, if I know the name of a function ("foo"), is there any way I can get the pointer to the function using that name and call it? I stumbled across a similar question for python here and it seems it is possible there. I want to take the name of a function as input from the user and call the function. This function does not have to take any arguments.
For Objective-C methods, you can use performSelector… or NSInvocation, e.g.
NSString *methodName = #"doSomething";
[someObj performSelector:NSSelectorFromString(methodName)];
For C functions in dynamic libraries, you can use dlsym(), e.g.
void *dlhandle = dlopen("libsomething.dylib", RTLD_LOCAL);
void (*function)(void) = dlsym(dlhandle, "doSomething");
if (function) {
function();
}
For C functions that were statically linked, not in general. If the corresponding symbol hasn’t been stripped from the binary, you can use dlsym(), e.g.
void (*function)(void) = dlsym(RTLD_SELF, "doSomething");
if (function) {
function();
}
Update: ThomasW wrote a comment pointing to a related question, with an answer by dreamlax which, in turn, contains a link to the POSIX page about dlsym. In that answer, dreamlax notes the following with regard to converting a value returned by dlsym() to a function pointer variable:
The C standard does not actually define behaviour for converting to and from function pointers. Explanations vary as to why; the most common being that not all architectures implement function pointers as simple pointers to data. On some architectures, functions may reside in an entirely different segment of memory that is unaddressable using a pointer to void.
With this in mind, the calls above to dlsym() and the desired function can be made more portable as follows:
void (*function)(void);
*(void **)(&function) = dlsym(dlhandle, "doSomething");
if (function) {
(*function)();
}