~Re: [Dev-C++] Question about class objects
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Abhijit S. <mu...@gm...> - 2002-10-23 13:00:55
|
Greets, Daniel.
> When I create a class object, can I call a member function right away?
>
> I'm thinking that if I have private data I want to initialise when the
> object is created I could put in a member function that does it, but can I
> call it immediately? Instead of
>
> MyClass ObjectOne;
> ObjectOne.StartUp();
>
>
> I know that a constructor initialisation list will do the same, can
someone
> show me an example of that as well as I am a little confused by the
syntax.
A constructor is basically a function that is called whenever an object of
the class is created. It's called in this case:
MyClass MyObject;
and also in this case:
pMyObject = new MyClass;
[-open-brace
But not here:
pMyObject = (MyClass *)malloc(sizeof(MyClass));
]-close-brace
The constructor should have the same name as the class, but no return type
(not void, it should have *no* return type), as in:
class MyClass
{
public:
MyClass(); // Constructor
~MyClass(); // Destructor
};
Constructors can take arguments, if necessary, like this:
MyClass(int some_foo);
You would invoke this constructor using
MyClass MyObject(666);
If you don't specify a constructor for a class, a default set of constructor
and destructor are provided for the class.
You don't have to explicitly call the constructor (in fact, you can't), it
is called whenever the object is created, and the destructor is called when
it goes out of scope. You can see the working if you write a test program
using cout within the constructor, something like this:
class foo
{
public:
foo()
{
cout << "The foo has risen.\n";
}
foo(int baz)
{
cout << "The foo has risen with " << baz
<< " coconuts.\n";
}
~foo()
{
cout << "The foo had you foolen. Now I will leave.\n";
}
}
and then creating objects using different means (static, dynamic).
___________________________________________________________
Abhijit Shylanath
E-mail: mu...@gm... || ibr...@bi...
Web-site: http://mudeth.tripod.com/
|