Use of Constructors - Odd Doubt - oop

I'm reading about constructors,
When an object is instantiated for a class, c'tors (if explicitly written or a default one) are the starting points for execution. My doubts are
is a c'tor more like the main() in
C
Yes i understand the point that you
can set all the default values using
c'tor. I can also emulate the behavior
by writing a custom method. Then why a c'tor?
Example:
//The code below is written in C#.
public class Manipulate
{
public static int Main(string[] args) {
Provide provide = new Provide();
provide.Number(8);
provide.Square();
Console.ReadKey();
return 0;
}
}
public class Provide {
uint num;
public void Number(uint number)
{
num = number;
}
public void Square()
{
num *= num;
Console.WriteLine("{0}", num);
}
}
Am learning to program independently, so I'm depending on programming communities, can you also suggest me a good OOP's resource to get a better understanding. If am off topic please excuse me.

Head First OOA&D will be a good start.
Dont you feel calling a function for setting each and every member variable of your class is a bit overhead.
With a constructor you can initialize all your member variables at one go. Isnt this reason enough for you to have constructors.

Constructor and Destructor functionality may be emulated using regular methods. However, what makes those two type of methods unique is that the language treats them in a special way.
They are automatically called when an object is created or destroyed. This presents a uniform means to handle the most delicate operations that must take place during those two critical periods of an object's lifetime. It takes out the possibility of an end user of a class forgetting to call those at the appropriate times.
Furthermore, advanced OO features such as inheritance require that uniformity to even work.

First of all, most answers will depend at least a bit on the language you're using. Reasons that make great sense in one language don't necessarily have direct analogs in other languages. Just for example, in C++ there are quite a few situations where temporary objects are created automatically. The ctor is invoked as part of that process, but for most practical purposes it's impossible to explicitly invoke other member functions in the process. That doesn't necessarily apply to other OO languages though -- some won't create temporary objects implicitly at all.

Generally you should do all your initialization in the constructor. The constructor is the first thing called when an instance of your class is created, so you should setup any defaults here.

I think a good way to learn is comparing OOP between languages, it's like seeing the same picture from diferent angles.
Googling a while:
java (I prefer this, it's simple and full)- http://java.sun.com/docs/books/tutorial/java/concepts/
python - http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/
c# - http://cplus.about.com/od/learnc/ss/csharpclasses.htm
Why constructors?
The main diference between a simple function (that also could have functions inside) and an Object, is the way that an Object can be hosted inside a "variable", with all it functions inside, and that also can react completly diferent to an other "variable" with the same kind of "object" inside. The way to make them have the same structure with diferent behaviours depends on the arguments you gave to the class.
So here's a lazy example:
car() is now a class.
c1 = car()
c2 = car()
¿c1 is exactly c2? Yes.
c1 = car(volkswagen)
c2 = car(lamborghini)
C1 has the same functionalities than C2, but they are completly diferent kinds of car()
Variables volkswagen and lamborghini were passed directly to the constructor.
Why a -constructor-? why not any other function? The answer is: order.
That's my best shot, man, for this late hours. I hope i've helped somehow.

You can't emulate the constructor in a custom method as the custom method is not called when the object is created. Only the constructor is called. Well, of course you can then call your custom method after you create the object, but this is not convention and other people using your object will not know to do this.
A constructor is just a convention that is agreed upon as a way to setup your object once it is created.

One of the reasons we need constructor is 'encapsulation',the code do something initialization must invisible

You also can't force the passing of variables without using a constructor. If you only want to instantiate an object if you have say an int to pass to it, you can set the default constructor as private, and make your constructor take an int. This way, it's impossible to create an object of that class without having it take an int.

Sub-objects will be initialized in the constructor. In languages like C++, where sub-objects exist within the containing object (instead of as separate objects connected via pointers or handles), the constructor is your only chance to pass parameters to sub-object constructors. Even in Java and C#, any base class is directly contained, so parameters to its constructor must be provided by your constructor.
Lastly, any constant (or in C#, readonly) member variables can only be set from the constructor. Even helper functions called from the constructor are unable to change them.

Related

What's wrong with hiding virtual method of a base class?

I have been getting Delphi compiler warnings about Method 'Create' hides virtual method of base.
I have reviewed several Stack Overflow links (see below), and I don't understand the logic behind this warning, and why it is considered bad coding practice. I'm hoping others can help me understand
I will include some sample code:
type
TMachine = class(TPersistent)
private
public
Horsepower : integer;
procedure Assign(Source : TMachine);
end;
...
procedure TMachine.Assign(Source : TMachine);
begin
inherited Assign(Source);
Self.Horsepower := Source.HorsePower;
end;
This causes the compiler warning.
[dcc32 Warning] Unit1.pas(21): W1010 Method 'Assign' hides virtual method of base type 'TPersistent'
I have been ignoring this warning because it didn't make any sense to me. But that got me in trouble in another way (see my other post here: Why does Delphi call incorrect constructor during dynamic object creation?) so I have decided to try to understand this better.
I know that if I use the reserved word reintroduce, the error will go away, but I have seen it repeatedly posted that this is a bad idea. As Warren P wrote here (Delphi: Method 'Create' hides virtual method of base - but it's right there), "IMHO, if you need reintroduce, your code smells horrible".
I think I understand what is meant by "hiding". As David Heffernan said here (What causes "W1010 Method '%s' hides virtual method of base type '%s'" warning?):
What is meant by hiding is that from the derived class you no longer have access to the virtual method declared in the base class. You cannot refer to it since it has the same name as the method declared in the derived class. And that latter method is the one that is visible from the derived class.
But I am somewhat confused because it seems that ancestor method is not really hidden, because a derived class can always just use the inherited keyword to call the method in the base class. So 'hidden' really means 'somewhat hidden'?
I think I also understand that using the reserved word override will prevent the compiler warning, but the procedure signature has to be the same (i.e. no newly added parameters). That I can't use that here.
What I don't understand is why hiding is something to be warned about. In my code example above, I would not want users of TMachine.Assign() to instead somehow use TPersistent.Assign(). In my extended class, I have extended needs, and therefore want to them to use the new and improved function. So it seems like hiding the older code is exactly what I want. My understanding of a virtual method is one where the correct method is called based on the actual type of an object at run time. I don't think that should have any bearing in this case.
Additional code, to be added to example code above
TAutomobile = class(TMachine)
public
NumOfDoors : integer;
constructor Create(NumOfDoors, AHorsepower : integer);
end;
...
constructor TAutomobile.Create(ANumOfDoors, AHorsepower : integer);
begin
Inherited Create(AHorsepower);
NumOfDoors := ANumOfDoors;
end;
This adds new compiler warning message: [dcc32 Warning] Unit1.pas(27): W1010 Method 'Create' hides virtual method of base type 'TMachine'
I especially don't understand problems that arise with using new constructors with additional parameters. In this post (SerialForms.pas(17): W1010 Method 'Create' hides virtual method of base type 'TComponent'), the wisdom seems to be that a constructor with a different name should be introduced, e.g. CreateWithSize. This would seem to allow users to pick and choose which constructor they want to use.
And if they choose the the old constructor the extended class might be missing some needed information for creation. But if, instead, I 'hide' the prior constructor, it is somehow bad programming. Marjan Venema wrote about reintroduce in this same link: Reintroduce breaks polymorphism. Which means that you can no longer use meta classes (TxxxClass = class of Tyyy) to instantiate your TComponent descendant as its Create won't be called. I don't understand this at all.
Perhaps I need to understand polymorphism better. Tony Stark wrote in this link (What is polymorphism, what is it for, and how is it used?) that polymorphism is: "the concept of object oriented programming.The ability of different objects to respond, each in its own way, to identical messages is called polymorphism." So am I presenting a different interface, i.e. no longer an identical message, and thus this breaks polymorphism?
What am I missing? In summary, isn't hiding base code a good thing in my examples?
The danger here is that you might call Assign on a base class reference. Because you did not use override then your derived class method is not called. You have thus subverted polymorphism.
By the principle of least surprise you should use override here, or give your derived class method a different name. The latter option is simple. The former looks like this:
type
TMachine = class(TPersistent)
public
Horsepower : integer;
procedure Assign(Source : TPersistent); override;
end;
...
procedure TMachine.Assign(Source : TPersistent);
begin
if Source is TMachine then begin
Horsepower := TMachine(Source).Horsepower;
end else begin
inherited Assign(Source);
end;
end;
This allows your class to co-operate with the polymorphic design of TPersistent. Without using override that would not be possible.
Your next example, with virtual constructors is similar. The entire point of making a constructor virtual is so that you can create instances without knowing their type until runtime. The canonical example is the streaming framework, the framework that processes .dfm/.fmx files and creates objects and sets their properties.
That streaming framework relies on the virtual constructor of TComponent:
constructor Create(AOwner: TComponent); virtual;
If you want a component to work with the streaming framework, you must override this constructor. If you hide it, then the streaming framework cannot find your constructor.
Consider how the streaming framework instantiates components. It does not know about all the component classes it needs to work with. It cannot, for instance consider third party code, the code you write. The Delphi RTL cannot know about types defined there. The streaming framework instantiates components like this:
type
TComponentClass = class of TComponent;
var
ClassName: string;
ClassType: TComponentClass;
NewComponent: TComponent;
....
ClassName := ...; // read class name from .dfm/.fmx file
ClassType := GetClass(ClassName); // a reference to the class to be instantiated
NewComponent := ClassType.Create(...); // instantiate the component
The ClassType variable holds a meta class. This allows us to represent a type which is not known until runtime. We need the call to Create to be dispatched polymorphically so that the code in the component's constructor is executed. Unless you use override when declaring that constructor, it won't be.
Really, all of this boils down to polymorphism. If your understanding of polymorphism is not firm, as you suggest, then you will struggle to appreciate any of this. I think your next move is to get a better grip on what polymorphism is.
There are different benefits for using inheritance. In your examples you do it to avoid coding the same things again and again. So if TMachine has Horsepower field already and some methods and now you need more advanced TAutomobile with NumOfDoors, you make it TMachine descendant.
If you now always treat them differently, i.e in some code you use exactly TMachine (machine := TMachine.Create(...), machine.Assign(AnotherMachine) etc. ) and in another code you use TAutomobile and they never get mixed
then you're all right, you can ignore these warnings or 'mute' them with reintroduce.
But there is usually another aspect of inheritance: keeping uniform interface, or as it's sometimes called: 'contract'. Separating interface from implementation.
For example, form is able to free all the objects which belong to it, no matter what these objects are, that's because of Destroy method which gets overrided. Form doesn't care about your implementation, but it knows: to free the object it just have to call Destroy, that easy. If you don't override Destroy, that's extremely bad: no way TForm will call you as TMachine.Destroy. It'll call you as TObject.Destroy, but it won't lead to your TMachine.Destroy, so you get a memory leak. In most cases when some method wasn't overriden it's just because programmer forgot to do it, thus a warning: it's very helpful one. If programmer didn't forget it but that was intentionally, reintroduce keyword is used. This way programmer tells: "Yes, I know what I do, this is intentionally, don't disturb me!"
TPersistent.Assign is another procedure which is frequently called from base class, not derived (that is: we don't want to pay attention to implementation, we just want to copy an object, whatever it is). For example, TMemo has Lines: TStrings, but TStrings is an abstract class, while the actual implementation is TStringList. So, when you write Memo1.Lines.Assign(Memo2.Lines), the TStrings.Assign method is used. It may implement this assign through another methods: clear itself first and then add line after line. Some TStrings descendant may want to speed-up process by some block copy of data. Of course it has to use exactly Assign(Source: TPersistent) method and override it, otherwise it is never called (inherited is called instead).
Classic implementation of Assign is like this:
procedure TMachine.Assign(Source : TPersistent);
begin
if Source is TMachine then
Horsepower := TMachine(Source).Horsepower
else inherited Assign(Source);
end;
That's the case when inherited shouldn't be called first thing. Here it is 'the last resort': it's called last if nothing else helped. It makes one final try: if your class don't know how to assign, maybe that Source knows how to AssignTo your class?
For example, TBitmap was coded long, long ago. After that TPngImage was developed to work with, well, PNG. You want to put PNG into bitmap and write: Bitmap.Assign(PngImage). No way TBitmap may know how to deal with PNG: it didn't exist back then! But TPngImage writer knew that may happen and implemented AssignTo method which is able to convert it to bitmap. So TBitmap as the last straw calls TPersistent.Assign method and that in turn calls TPngImage.AssignTo and that works like a charm.
Is this side of inheritance needed in your program is up to you. If there is again lots of dublicating code (the one which deals with machines and another with automobiles) or there are lots of conditions, then something is wrong and some good polymorphism might be of help.

Singleton use within objects or passed as reference

I program in PHP but this is a general Object orientation question.
What do we feel about calling singleton classes from within an object vs calling one outside and passing the variable in?
Option one:
$instance = Singleton::getInstance();
$obj = new ClassName();
$obj->setSingleton($instance);
Option two:
class ClassName
{
public function __construct(){
$instance = Singleton::getInstance();
$instance->doSomething();
}
}
Is this just a "per-use" decision (i.e. singleton implementing interface, etc) or are there rules?
I can see passing objects VS singletons but one about singleton instances vs calling? Think typical code with lots of classes and many uses for the singleton instance... Are there any rules for this?
Either is fine, but when others will look at your code it might be less obvious they're dealing with a singleton in your option #1, especially if the code grows big. IMHO it's perfectly valid to keep a reference of your singleton in the body of a function when you need to call it a few times in a row, but I wouldn't keep it as member variable.
Keeping a member variable also implies your objects will be bigger for no apparent reason.

When should I use static methods in a class and what are the benefits?

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need to call a method of a class, I create an object of that class and call the desired method.
Q: Static variable in a method holds it's value even when method is executed but accessible only in its containing method but what is the best definition of static method?
Q: Is calling the static method without creating object of that class is the only benefit of static method?
Q: What is the accessible range for static method?
Thanks
Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something.
Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:
// This makes little sense
Math m = new Math();
float answer = m.sin(45);
// This would make more sense
float answer = Math.sin(45);
In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C.
Static methods don't pass a "this" pointer to an object, so they can't reference non-static variables or methods, but may consequently be more efficient at runtime (fewer parameters and no overhead to create and destroy an object).
They can be used to group cohesive methods into a single class, or to act upon objects of their class, such as in the factory pattern.
Syntax (php) for static methods:
<?php
class Number {
public static function multiply($a, $b) {
return $a * $b;
}
}
?>
Client code:
echo Number::multiply(1, 2);
Which makes more sense than:
$number = new Number();
echo $number->multiply(1, 2);
As the multiply() method does not use any class variables and as such does not require an instance of Number.
Essentially, static methods let you write procedural code in an object oriented language. It lets you call methods without having to create an object first.
The only time you want to use a static method in a class is when a given method does not require an instance of a class to be created. This could be when trying to return a shared data source (eg a Singleton) or performing an operation that doesn't modify the internal state of the object (String.format for example).
This wikipedia entry explains static methods pretty well: http://en.wikipedia.org/wiki/Method_(computer_science)#Static_methods
Static variables and static methods are bound to the class, and not an instance of the class.
Static methods should not contain a "state". Anything related to a state, should be bound to an instantiated object, and not the class.
One common usage of static methods is in the named constructor idiom. See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8.
Static Methods in PHP:
Can be called without creating a class object.
Can only call on static methods and function.
Static variable is used when you want to share some info between different objects of the class.As variable is shared each object can update it and the updated value be available for all other objects as well.
As static variable can be shared,these are often called as class variable.
static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.
Static elements are available in every instance of a class, so you can set values that you want to be available to all members of a type.
for further reading a link!

Why should member variables be initialized in constructors?

When I first started working with object-oriented programming languages, I was taught the following rule:
When declaring a field in a class, don't initialize it yet. Do that in the constructor.
An example in C#:
public class Test
{
private List<String> l;
public Test()
{
l = new List<String>();
}
}
But when someone recently asked me why to do that, I couldn't come up with a reason.
I'm not really familiar with the internal workings of C# (or other programming languages, for that matter, as I believe this can be done in all OO languages).
So why is this done? Is it security? Properties?
If you have multiple constructors, you might want to initialize a field to different values
When you initialize the field in the constructor, there can be no confusion over when exactly it is initialized in regard to the rest of the constructor. This may seem trivial with a single class, but not so much when you have an inheritance hierarchy with constructor code running at each level and accessing superclass fields.
The C# compiler will take any non-static member intialization that you do inline and move it into the constructor for you. In other words this:
class Test
{
Object o = new Object();
}
gets compiled to this:
class Test
{
Object o;
public Test()
{
this.o = new Object();
}
}
I am not sure how compilers for other languages handle this but as far as C# is concerned it is a matter of style and you are free to do whichever you wish. Please note that static fields are handled differently: read this article for more information on that.
One reason to do it is that it puts all of the initialization code in one place which is convenient for others reading your class. Having said this I don't really do it for two primary reasons. (1) I use TDD/Unit testing to define the behavior of my class. If you want to know what the parameterless constructor does, you should really read the tests I've built on the parameterless constructor. (2) With C# 3.0, I typically use automatic properties and inline initialization with a parameterless constructor to instantiate the object. This is much more flexible and it puts the definition of the properties right in line where the code is being used. This would override any initialization in the constructor so I rarely put any there. Of course, this only applies to C#.
Ex. (of 2)
var foo = new Foo { Bar = "baz" };
public class Foo
{
public string Bar { get; set; }
public Foo() { }
}
sometimes the constructor has parameters that are used for initializing internal variables. For example size of arrays
I haven't heard a compelling reason to not offer both options. I suspect that the real reason has to do with simplifying the language structure from a parsing perspective. This is especially true in C-derivative languages where parsing an assignment statement requires 75% of the language syntax rules. It seems to me that allowing it and defining how it would work precisely would be nice. I agree with Michael's comment about the complexity increase as you insert inheritance and multiple constructors but just because you add a feature doesn't mean that you have to use it. I would vote to support both even though my vote doesn't really add up to much.
I always like to think of the class as a factory for objects, and the constructor as the final stop on the production line. The fields declared in the class are blueprints descirbing the object, but the blueprint won't be realised into an object before such an object is ordered tthrough a call to the constructor... Also, as someone pointed out, doing all your initialisations in your constructor will improve readability, as well as it wil provide for dynamicity in initialisation (it might not be a parameterless constructor you're dealing with).
Also, in some languages the constructor may be used for resetting an object to an original state, which is why it will then be necessary to instatiate the object in the constructor.

What's wrong with Copy Constructors? Why use Cloneable interface?

When programming C++ we used to create copy constructors when needed (or so we were taught). When switching to Java a few years ago, I noticed that the Cloneable interface is now being used instead. C# followed the same route defining the ICloneable interface. It seems to me that cloning is part of the definition of OOP. But I wonder, why were these interfaces created, and the copy constructor seems to have been dropped?
When I thought about it, I came to the thought that a copy constructor would not be useful if one needs to make a copy of an object whose type is not known (as in having a reference to a base type). This seems logical. But I wonder whether there are other reasons that I do not know of, for which the Cloneable interfaces have been favored over copy constructors?
I think it's because there is no such inherent need for a copy constructor in Java and in C# for reference types. In C++ objects are named. You can (and you will most often) copy (and in C++1x move) them around e.g when returning from functions, since returning pointers require you to allocate dynamic memory which would be slow and painful to manage. The syntax is T(x) so it makes sense to make a constructor taking a T reference. C++ couldn't make a clone function, since that would require returning an object by value again (and thus another copy).
But in Java, objects are unnamed. There are only references to them, which can be copied, but the object itself isn't copied. For the cases when you actually need to copy them, you can use the clone call (but i read in other anwers clone is flawed. i'm no java programmer so i cannot comment that). Since not the object itself is returned, but rather a reference to it, a clone function will suffice. Also a clone function can be overriden. That's not going to work with copy constructors. And incidentally, in C++ when you need to copy a polymorphic object, a clone function is required too. It's got a name, the so-called virtual copy constructor.
Because C++ and Java (and C#) aren't the same thing. C++ has no built-in interfaces because interfaces aren't part of the language. You can fake them with abstract classes but they aren't how you think about C++. Also, in C++ assignment is normally deep.
In Java and C# assignment just involves copying the handle to the internal object. Basically when you see:
SomeClass x = new SomeClass();
in Java or C#, there's a level of indirection builtin that doesn't exist in C++. In C++, you write:
SomeClass* x = new SomeClass();
Assignment in C++ involves the dereferenced value:
*x = *another_x;
In Java you can get access to the "real" object as there is no dereference operator like *x. So to do a deep copy, you need a function: clone(). And both Java and C# wrapped that function into an interface.
It's the issues of final type and of cascading the clone operation through the super classes which is not addressed by copy constructors - they are not extensible. But the Java clone mechanism is widely considered badly broken too; especially problems where a subclass does not implement clone(), but inherits from a superclass that implements cloneable.
I strongly recommend you research cloning carefully, whatever path you choose - you will likely choose the clone() option, but make sure you know exactly how to do it properly. It's rather like equals() and hashCode() - looks simple on the surface, but it has to be done exactly right.
I think you haven't get the right point. I give you my two cents.
Fundamentally there's a problem: creating a clone of a class without knowing the exact class type. If you use copy constructor, you cannot.
Here is an example:
class A {
public A(A c) { aMember = c.aMember }
int aMember;
}
class B : A {
public B(B c) : base(c) { bMember = c.bMember }
int bMember;
}
class GenericContainer {
public GenericContainer(GenericContainer c) {
// XXX Wrong code: if aBaseClass is an instance of B, the cloned member won't
// be a B instance!
aBaseClass = new A(c.aBaseClass);
}
A aBaseClass;
}
The Clone method, if declare virtual, could create the right class instance of the generic member.
An this problem is common to every language, C# C++ or Java...
Maybe this is what you was meaning, but I cannot understand this from any answer.
Just wanted to add that in Java the copy constructor is not completely useless.
There are cases where your class has a private instance variable of a mutable non-final type, e.g. Date, and has a setter and getter for the variable. In the setter, you should make a copy of the given date, because the caller could modify it later and thereby manipulate your object's internal state (usually by accident, but maybe intentional). In the getter, the same precaution is required.
The defensive copy could be implemented by calling clone() (the class Date is cloneable), but a malicious caller could call the setter with a subclass of Date which overrides the clone() method with {return this;}, and so the caller might still be able to manipulate your object. This is where the copy constructor comes into play: By calling new Date(theDate), you are sure to get a fresh Date instance with the same timestamp as the given date, without any connection between the two date instances. In the getter, you could use the clone method, because you know the private variable will be of class Date, but for consistency, usually the copy constructor is used there, too.
Also note that the copy constructor would note be required if the Date class was final (calling clone() were safe) or immutable (no copy required).
I think its only because once u have defined a copy constructor, you could never pass the reference itself again. (Unless it would have a function that does that...but thats not any easier than using the clone() method.)
In C++ its not a problem: you can pass the whole object or its reference.