LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-22-2006, 03:46 AM   #1
runnerpaul
Member
 
Registered: Mar 2006
Location: Ireland
Distribution: Fedora 5
Posts: 67

Rep: Reputation: 15
What is a constructor?


I recently started programming in Java again. When in uni I learned what a constructor was but have to admit I never really understood it. Can anybody explain what a constructor is(in simple terms) and tell me how to know when to use one.
 
Old 09-22-2006, 04:17 AM   #2
NomadX
Member
 
Registered: Jul 2005
Location: Portland, OR
Distribution: Debian Testing
Posts: 78

Rep: Reputation: 15
http://en.wikipedia.org/wiki/Constru...ter_science%29

Anytime you want to create a new instance of your class (an object) the constructor will be automaticaly called to initialize the variables used or to allocate some memory. It's basicaly a prototype for classes.

I never took computer science, perhaps thats not technicaly correct, but thats the jist of it.. There's a good definition on that url, but heres a better example from a tutorial I have:

// example: class constructor
#include <iostream>
using namespace std;

class CRectangle {
int width, height;
public:
CRectangle (int,int);
int area () {return (width*height);}
};

CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}

int main () {
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

CRectangle::CRectangle is the constructor there...

Last edited by NomadX; 09-22-2006 at 04:21 AM.
 
Old 09-22-2006, 02:12 PM   #3
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
DrStoney hit it right on. the only thing i would change is to say is that the constructor is not "automatically" called, you have to explicitly call a constructor to create an instance. just like was showed in the example, you call the two int constructor and it creates a rect of given size.
 
Old 09-22-2006, 08:58 PM   #4
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,659
Blog Entries: 4

Rep: Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941
A good way to think of "an object," in any language, is that it is a chunk of memory which has procedural code magically associated with it. That is, conceptually, how such things are implemented.

So, when we want our language to "create an object," what it actually does is to carve out a new block of memory, set up the magical pointers and stuff which allows that block of memory to "be an object," and then ... well, the object might have various needs of its own for setting things to initial values, initializing other objects that it might need, and so on. So, that's what a "constructor" does. It's an initialization routine. After allocating the memory and doing the magic, each of the constructors are run.

Likewise, when an object is being destroyed, "what the object might have initialized in its constructor, now needs to be dismantled." That's what a "destructor" is for: it's a termination or cleanup routine. So, if (for example) the constructor allocated a few other objects that it needed, then its destructor should dispose of those things. Once the destructor(s) associated with an object have finished executing, the object itself goes away.
 
Old 09-23-2006, 01:01 AM   #5
NomadX
Member
 
Registered: Jul 2005
Location: Portland, OR
Distribution: Debian Testing
Posts: 78

Rep: Reputation: 15
Hmm... ok I'll bite.. so when your using an object, you are "constructing" it? I said automaticaly because I figure passing the variables to the object is done with out creating the Classname::Classname bit again... The terminology of this stuff is harder then doing it! Heh
 
Old 09-23-2006, 01:56 AM   #6
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
the object must be constructed before it can be used,...

The whole point of constructors is that you cannot use the object until you have successfully constructed it.

The comp sci terminology is "invariant":
Quote:
A class describes a collection of encapsulated instance variables and methods (functions), possibly with implementation of those types together with a constructor function that can be used to create objects of the class...
Quote:
A class also describes a set of invariants that are preserved by every method in the class. An invariant is a constraint on the state of an object that should be satisfied by every object of the class...
The main purpose of a constructor is to establish the invariant of the class, failing if the invariant isn't valid. The main purpose of a destructor is to destroy the identity of the object, invalidating any references in the process...
http://en.wikipedia.org/wiki/Class_(computer_science)

PS:
Although this is most common way you'll see a constructor invoked:
Code:
MyClass *myObject = new MyClass ();
it's entirely possible to have a constructor ... and invoke it ... *without* making it look like a function:
Code:
static MyClass myObject; // This is perfectly valid ...
                         // ... provided there's a zero-argument constructor defined for the class

Last edited by paulsm4; 09-23-2006 at 02:03 AM.
 
Old 09-23-2006, 10:54 AM   #7
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
> it's entirely possible to have a constructor ... and invoke it ... *without* making it look like a function:

yeh i guess what i said up above could be taken either way. its probably a perception thing, my comment was probably more confusing than helpful.

in my mind though this
Code:
class Foo{};
int main()
{
    Foo f;
    return 0;
}
is explicitly calling the no arg constructor.. but i guess it could be said to be implicitly calling it as well..

Last edited by xhi; 09-23-2006 at 10:56 AM.
 
Old 09-23-2006, 11:38 AM   #8
Dan04
Member
 
Registered: Jun 2006
Location: Texas
Distribution: Ubuntu
Posts: 207

Rep: Reputation: 37
Quote:
Originally Posted by paulsm4
it's entirely possible to have a constructor ... and invoke it ... *without* making it look like a function:
Code:
static MyClass myObject; // This is perfectly valid ...
                         // ... provided there's a zero-argument constructor defined for the class
That's true in C++, but not in Java.
 
Old 09-23-2006, 11:48 AM   #9
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
Quote:
Originally Posted by Dan04
That's true in C++, but not in Java.
very true... i also had forgotten which language we were talking about.

in that case i once again agree with my first post.. ive got to stop arguing with myself like this..
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
No virtual constructor in C++ Why??? krishnacins Programming 10 04-11-2006 09:19 PM
Copy constructor in C++ prenayan Linux - General 3 11-13-2003 02:48 PM
c++ constructor question jhorvath Programming 6 11-06-2003 10:52 PM
Class constructor not being called ChimpFace9000 Programming 1 06-03-2002 08:54 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:54 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration