user7982333
user7982333

Reputation:

Are constructors used to initialize the object itself?

I was wondering if a constructor is used to initialize the object itself? To make this question more understandable, here is an example:

class xx 
{
   int w;
   int a;
    xx();
};  
xx::xx() 
{
    cout << "new object created";
}

So when declaring the object:

xx objy;

the default constructor is called(which we in this case has redefined, correct me if I am wrong, please). Can you say that the constructor initializes the object "objy" or what to say about the initialization of this object? Btw. if the constructor does not initialize the object, it is just used for performing certain actions needed as soon as the object is created, right?

More: For some people, like me, it can seem very odd that some of the "pros" claims that a constructor, such as this one:

xx::xx() 
{

}

still has an effect on the class object that has been created.

For instance, I do not understand how a constructor like the one above can put the object "objy" in "its initial state"(what does it mean to be in the initial state? :/ ) even though there is nothing inside its block.

-- Hope someone gets my point now. Otherwise, please ask more examples or something like that.

Thanks!

Upvotes: 1

Views: 460

Answers (2)

Dr t
Dr t

Reputation: 247

In the case of your example the story would be something like this:

The process encounters your code that uses the name of the class definition as a data type. "xx objy;"

At that point the process communicates with the OS asking for enough contiguous memory to hold the thing that you are talking about (an instance of the class with the name 'objy'). Upon finding that memory space the OS returns the beginning address of that memory location to the process and the process assigns and binds that address to the name (which is a named address aka pointer)

Since in your example you have simply rewritten the default constructor to produce some console output (which is perfectly fine) there are no initializations made to member variables (states) etc.

Your instance is now in an initial valid state...

Edit and update:

Since your class definition is empty, the instance will not require any memory, so essentially nothing will happen.

Refer to: C++11 standard 12.1.5: and 12.8.7, 12.8.11: and 12.8.18, 12.8.20, 12.8.22:

Upvotes: 0

Jesper Juhl
Jesper Juhl

Reputation: 31467

The job of the constructor is to initialize an object instance to a valid state.

The default constructor by default does nothing but default initialize all members.

If the object has members that need more than default initialization to be valid, then the compilers default constructor is not going to cut it and it is your job to write a constructor that does whatever is needed to initialize those members.

Upvotes: 2

Related Questions