Constructors

Pages: 12
What advantage is there to using my own constructor to using the default constructor?

And am i right in thinking that constructors are functions which initialise instances of classes (objects)?
Constructors are there so that object is in a well defined, valid state after being created. What well defined, valid means however depends on the context of the class you are using.
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.1
Last edited on
Any self-made class will require a constructor. As far as I know (I'm a beginner myself), the entire point of constructors is a) initializing class members on object creation and b) allowing for assignment of starting values to these members.

Easy example: a class "Circle" with as only member "int Radius". A default constructor (no parameters and no content) will make the object, but keep the member variables unitialized. Any call to the value of the Radius member will result in errors (or worse).

Your constructor can also immediately assign default values (e.g. initialize Radius as 0 once a new Circle object is made), or even assign a specified value to the Radius member by passing the value as a parameter. This way, the created object can be used immediately without the need for calling set() methods first.
Your constructor can also immediately assign default values (e.g. initialize Radius as 0 once a new Circle object is made), or even assign a specified value to the Radius member by passing the value as a parameter. This way, the created object can be used immediately without the need for calling set() methods first.


That's done in the initialization list, not in the constructor body though, I think we should mention that.
Ok, so basically a constructor is a function that initilizes the members of an object. Lets look at this:

GameEngine(HINSTANCE hInstance, LPTSTR szWindowClass, LPTSTR szTitle,
WORD wIcon, WORD wSmallIcon, int iWidth = 640, int iHeight = 480);

So this is a constructor. I have a few questions:

1. I suppose this first question doesnt really matter, but, when we compile, are the member variables initialised there and then, or are they initialised when we create an instance of the class?

2. Are the parameters the member variables we want to initialise?

3. In my class i have made two other member variables which are not included in this constructor, could you tell me why i havnt included them in this constructor to initialise them, they are static GameEngine* m_pGameEngine; & HWND m_hWindow;?

4. So its a must that i have to use a constructor to initialise member variables for a self made class, always?

So i can read your replies easily could you number your replies accordingly to my questions.

Thanks :D
Last edited on
1. When the object/instance is created. This is obvious, since members are object-specific. There is no point in having a Name and Age member if they're not attached to a Person object!

2. Depends. You can initialize members by passing a value as a constructor parameter, or by giving it a default value.

For example, a Person with Name and Age members. If you make an object of this class, you need to assign a value to Name and Age, so you could have a constructor that accepts Name and Age parameters. However, if a person is added at birth, then his age will always be 0, thus it would be sufficient to call a constructor that only requires a Name parameter and have the constructor simply set Age to 0. Or you could call the constructor with two parameters and pass 0 for age.

3. Sorry, no idea.

4. To create an object you always (?) need to call a constructor method. You don't HAVE to initialise every member (you can use set() methods afterwards), but in my eyes it's best to make sure every member is initialized at object creation to prevent any oddities as a result of calling the value of uninitialized variables.
I suppose this first question doesnt really matter, but, when we compile, are the member variables initialised there and then, or are they initialised when we create an instance of the class?


Member variables belong to instances, not to classes. So they are initialized on runtime when you create an instance.

2. Are the parameters the member variables we want to initialise?

Not necessarily. Your constructor should always initialize ALL member fields, but it doesn't need to take a parameter for each and every member field, rather you'd probably set default values for most member fields, or deduct them from something else than parameters (ex: create a new pointer to a buffer with new)

In my class i have made two other member variables which are not included in this constructor, could you tell me why i havnt included them in this constructor to initialise them, they are static GameEngine* m_pGameEngine; & HWND m_hWindow;?


Depends on what you use them for, but from context I'd deduct that HWND &m_hWindow is the window handle of the window that you create in the constructor, and static GameEngine* m_pGameEngine is a class member, not an instance member, so of course you wouldn't initialize it in the constructor for instances. It probably returns a previously created GameEngine... looks like GameEngine is supposed to be a singleton.

4. So its a must that i have to use a constructor to initialise member variables for a self made class, always?


It's technically not always necessary (as a matter of legality), practically you should always write one (as a matter of morality). Always and never are relative btw, if something is legal there might be situations in which it is appropitiate to do it, but that's something you will have to decide on a case by case basis. What you should remember is that nontrivial classes usually need a constructor to function properly.
You said they are both a "class member, not an instance member, so of course you wouldn't initialize it in the constructor for instances".

Do we only initialise members variables which our instances of the class (objects) will use?

What about the members variable which we dont initialise which the objects wont use, are they still usable, how would we use the hWindow member variable, would we put something like GameEngine.hWindow?

static members are specific to the class, not to the instance. They are globally initialized like that:
1
2
3
4
5
6
class Foo
{
private:
static int bar;
}
int Foo::bar=5;


You can access bar from anywhere where the class Foo is known, e.g.
1
2
3
Foo foobar;
cout<<foobar.bar; //5
cout<<Foo::bar; //5 
Last edited on
Ok, so we initialise variables within a class which we use for instances with a constructor.

And we do not use a constructor on members which are for specific use to the class, we access the variable for the class with the scope resolution operator.

In my head, at the moment, we initialise member variables for objects to give them variables "life", so as we dont have to give class specific variables "life" could you tell me why we dont have to do this.

Thanks
could you tell me why we dont have to do this.


You misunderstand me, you have to do this for static variables, just not in the constructor. The constructor is for creating instances, however static variables belong to the classes, not to the instances. The initialization for static variables is only done once, outside of the class with the following syntax:

 
type_of_static name_of_class::name_of_static = initial_value;
Ok, hopefully this is my last two questions on this:

1. Cant static variables be initialised in the class?

2. So to summarise, static members are for class use, as they are members which only exist once in a program which means that objects CANT each have that member, they would each be sharing that variable if we did actually initialise it in the constructor,

and instance members are for instances/objects use
Last edited on
Cant static variables be initialised in the class?

static constants can, actually. The others, no. Also, even the outside-class-= stuff only works under certain circumstances. See here for details:

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.11

So to summarise, static members are for class use, and instance members are for instances/objects use


Not necessarily. static functions and objects are objects and functions that you only need exactly one copy of, no matter how many actual instances of the class exist. They could also be used to share common data between all instances of an object. A simple example is the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class X
{
private:
int nr;
static int count;
public:
X() : nr(count)
{
++count;
}
int getID(){return nr;}
static int getCount(){return count;}

};
int X::count = 0;


In this example, all instances of X receive a unique ID upon creation, and getCount will return the number of all objects of X created (note: not the count of the ones that actually exist at the moment)

another prominent example is the Singleton:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Singleton
{
private:
static Singleton *instance;
Singleton(){}
public:
static Singleton& getInstance()
{
if(instance==0)
{
instance = new Singleton;
}
return *instance;
}
};

Singleton* Singleton::instance = 0;


Which makes sure that only one instance of singleton is ever created.
Last edited on
:D

With destructors, do they work in the exact same way, to delete a initialised member called int m would you put:

~GameEngine(int m);

What happens if i leave the parameters empty, does it delete all or none?

and my book writes the word "virtual" before this destructor and puts the "s" letter after the destructor, anyone care to explain why :D?

You cannot pass parameters to the destructor. It's sole purpose is to perform clean up for the object - generally, that means delete'ing anything you have new'd in the constructor.

About virtual destructors:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7
Ok, what if i had 3 instances of a class but i only wanted to perform clean up on 1 of them objects, how would i do that?
Ok, what if i had 3 instances of a class but i only wanted to perform clean up on 1 of them objects, how would i do that?


Destructors are only invoked on objects that are to be destroyed, ex:
1
2
3
4
5
Object a; //Constructor is called for a
Object *b;
b = new Object; //Constructor is called for b (after memory has been assigned to b);
delete b; //Destructor is called for b (and then the memory is freed)
} //destructor is called for a because a leaves it's scope 
Ok, so to destruct a specific object we use the delete keyword,

and if an object leaves its scope the destructor is automatically called right?

and by scope, do you mean off-screen?
Last edited on
Am i correct? :D
Only use the "delete" keyword for objects created with the "new" keyword.

Out of scope means "once the method that called it has finished".

Using hanst99's previous example:
1
2
3
4
5
void CreateObjectAndCout() {
Foo foobar;
cout<<foobar.bar; //5
cout<<Foo::bar; //5
}


Calling the method CreateObjectAndCout() will create the object (=call the constructor and thus initialize its members), perform the couts and then automatically destroy the object (=call the destructor), because the method that created it (= "CreateObjectAndCout") has ended, thus the object has "served its purpose".

I'm not sure if you can manually destroy an object that wasn't created by using "new".
Last edited on
Pages: 12