Solved

C++ Default Constructor

Posted on 2010-11-24
14
619 Views
Last Modified: 2013-11-17
Hi,
I wondering what happens in the default constructor.
Let me say that I have a class as shown in the code section, why does compiler create a default constructor? and what happens in the default constructor if there is nothing to initialize?
My understanding of constructor is to initialize the member variables of the class. since the class shown below does not have any class members and it is not inherited, I am wondering why the compiler creates the default constructor and what code is placed inside this?
Similarly I want to know about what happens inside the Copyconstructor assignment operator and destructor also. Can please some one explain me this? this was an interview question and i am not getting any proper answers for this.
class A

{

};



int main()

{

  A objA;

  cout<<"Size of A: "<<sizeof(objA)<<endl;

}

Open in new window

0
Comment
Question by:yamurthy
  • 5
  • 5
  • 2
  • +1
14 Comments
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 34210842
The default constructor has no initializer list and a null body and it is created by the compiler if you don't supply one.
Distinct Memory has still got to be allocated since 2 objects of an empty class cannot have the same address. So memory has to be allocated and initialized. This is what the default constructor created by the compiler does.

I suggest you read the reasons Stroustrup gives for this scenario.

Point to be noted is that no default constructor is created for a class having any constant or reference type members.

We are talking memory initialization here so this needs to be done when an object is created and not necessarily only if the class has explicit variables.
0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 34210849
It shouldn't be difficult to figure out now why you would need a default Copy constructor, assignment operator etc....
0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 34210876
One more point is that a default copy constructor cannot be created if any of the class's members or its base classes have inaccessible copy constructor. So all these default constructors which the compiler provides are implicitly public and they are usually inlined.

Coming to uses, I can think of using empty classes to differentiate between exceptions, you don't need member data for this

Empty classes can also be used to differentiate between states in a control system

http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty
http://www.cantrip.org/emptyopt.html
0
 
LVL 1

Author Comment

by:yamurthy
ID: 34210907
Thanks trinitrotoluene, I need some more clarification...

"So memory has to be allocated and initialized"

What i believe is that the memory is allocated before the constructor is called. Is the "this" pointer initialized in the default constructor? or the memory zeroed. I think the memory is not zeroed. I don't have any reference. Please clarify.
0
 
LVL 53

Accepted Solution

by:
Infinity08 earned 400 total points
ID: 34210934
>> So memory has to be allocated and initialized. This is what the default constructor created by the compiler does.

This is not entirely accurate.

The memory allocation for the object will NOT be done by the constructor. That is the responsibility of the code where the object is instantiated (and depends on the way it's instantiated).

The only responsibility of a constructor is to initialize the object for use.

Since the question is about an empty object that doesn't have any data members or virtual member functions, and doesn't inherit from another class, the default constructor has nothing to do. So that's what it'll do : nothing.
The same is true for the default copy constructor and the default destructor.

Now, your question was : why do they need to be there if they do nothing ?
The reason is simple : because those three member functions need to be able to be called.

A lot of the code (and most importantly the C++ language and the STL) depend on the existence of these three member functions. They absolutely need to be defined, or the compiler will refuse to compile the code. So, you (or the compiler) has to provide them - even if they do nothing.
0
 
LVL 40

Assisted Solution

by:evilrix
evilrix earned 100 total points
ID: 34210942
Just to elaborate a little on what trinitrotoluene has already discussed...

>> why does compiler create a default constructor?

How else would the class get constructed?

>> what happens in the default constructor if there is nothing to initialize?

Very little but even if one doesn't exist the compiler will synthersise one since it is *the* function that constructs the object. Not only that the constructor is a function you can explicitly call to create temporary objects, without one you would not be able to do the following, for example:

MyClass const & ref = MyClass();

Open in new window


>> I am wondering why the compiler creates the default constructor and what code is placed inside this?

From our point of view we can consider the constructor to be empty but the compiler is at liberty to add whatever instrumentation it wishes into the constructor as long as the expected behavior is not modified. FOr example, a debug build may contain additional information used by the debugger - it's really up to the compiler vendor what they do as long as they don't modified the expected behaviour as defined by the standard documentation.

>> Similarly I want to know about what happens inside the Copyconstructor assignment operator and destructor also.

In terms of them being synthersised again very little. The destructor will perform whatever compiler specific requirements are needed so will the copy constructor. The copy-construtor will also contain code that performs a binary (shallow) copy of the class.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34210948
haha... I seen Infinity08 is typing quicker than me today :)
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:yamurthy
ID: 34211136
what about "this" pointer? who initializes "this" pointer. some one at some time the "this" pointer has to initialized right? my assumption was this happens in the default constructor. but from the explanation it looks like it does not happen there!! then where exactly it happens and who initializes it?

Also what happens if do delete "this" in the destructor?
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34211149
>> what about "this" pointer? who initializes "this" pointer

It's effectively the address of the class, when you call a member function the compiler just passes it in as an invisible first parameter that you do not see. For example, when you do this...

myclass.foo();

Open in new window


The compiler re-writes that as this...

myclass.foo(&myclass);

Open in new window


And your definition of foo() is this...

MyClass::foo(){}

Open in new window


But the compiler re-writes it to this...

MyClass::foo(MyClass const * this){}

Open in new window


This happens behind the scenes.

>> Also what happens if do delete "this" in the destructor?

Nothing, the function will still process as normal but at the point the instruction to delete is call all access to the "this" pointer becomes undefined. It is not a great idea to do that!
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 34211185
>> It is not a great idea to do that!

That's an understatement heh.

I'd answer :

>> Also what happens if do delete "this" in the destructor?

with : all kinds of bad things.

The problem is that :

(a) in the destructor you don't know how the object's memory has been allocated, so there's no way to know if the delete operator would be the right way to de-allocate the memory.

and more importantly :

(b) the de-allocation is performed outside of the destructor already. Trying to do it a second time is just asking for trouble.
0
 
LVL 40

Expert Comment

by:evilrix
ID: 34211232
>> in the destructor you don't know how the object's memory has been allocated

That's a good point - I should have been clear this will only apply if the object was constructed using new. Further, as I8 points out, if you are calling delete on the class anyway it will result in a double delete. If you call the destructor directly it won't... but as I said before, not a great idea to do this (unless you really know what you are doing - and I can't think of many use cases where this would be something you'd want to do).

>> That's an understatement heh.

Yeah, I probably under-sold that :)
0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 34211460
"So memory has to be allocated and initialized. This is what the default constructor created by the compiler does. "

yes that was a slip on my part. Thanks Infini for pointing it out.

Would like to add that it is therefore safe to access a class's data members within a constructor's body since it is guaranteed that all the members are fully constructed in memory by the time the body of the constructor executes. So a constructor's primary job as has been pointed out already is to just initialize.

0
 
LVL 40

Expert Comment

by:evilrix
ID: 34211483
>> it is therefore safe to access a class's data members

This is true - but the same cannot be said for virtual functions. Until the constructor is complete virtual functions to not implement polymorphic behaviour since the v-table will not be completely created at that point. The same is true for the destructor. In short, do not call virtual functions in the constructor or destructor - they will not do what you expect.
0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 34211516
"do not call virtual functions in the constructor or destructor - they will not do what you expect."

yes thats right you can never get down to a derived class from the body of  a base constructor by calling a virtual member function which is overridden in the derived class.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now