473,800 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why is the Constructor called 4 times but the Destructor 5 times?

Why is the Constructor called 4 times but the Destructor 5 times? I am
using MS VC 6. If this has been covered already please let me know.

The Code:

#include <stdio.h>

class MyClass {
private:
int x;
int y;
static int count;
int id;
public:
MyClass(int x=0,int y=0): x(x),y(y){
printf("Create (%d)\n",++count );
id = count;
}
~MyClass(){
printf("kill (%d)\n",id);
}
MyClass(const MyClass &r){
printf("Copy\n" );
x = r.x;
y = r.y;
}

void Set(int ix,int iy){
x = ix; y = iy;
}
void Print(){
printf("x=%d y=%d\n",x,y);
}

//operators
MyClass operator + (const MyClass &left){
printf("Start +\n");
MyClass temp;
temp.x = x + left.x; temp.y = y + left.y;
printf("End +\n");
return temp;
}
MyClass &operator += (const MyClass &left){
x += left.x; y += left.y;
return *this;
}
MyClass &operator += (int left){
x += left; y += left;
return *this;
}
MyClass &operator = (const MyClass &r){
x = r.x; y = r.y;
return *this;
}
};

int MyClass::count = 0;

int main(int argc,char **argv){

MyClass c1(5,6);
MyClass c2(1,1);
MyClass c3(100,200);

printf("before\ n");
c1.Print();
c2.Print();
c3.Print();

c3 = c1+ c2;

printf("after\n ");
c1.Print();
c2.Print();
c3.Print();
return 0;
}
Jul 19 '05 #1
9 1717

"djskrill" <cp*@twerd.co m> wrote in message news:f0******** *************** ***@posting.goo gle.com...
Why is the Constructor called 4 times but the Destructor 5 times? I am
using MS VC 6. If this has been covered already please let me know.


A constructor is called 5 times. After modifying your copy constructor to actually
initialize the id field:

MyClass& operator=(const MyClass& r) {
id = r. id;
x = r.x;
y = r.y;
}

This is what I get as output: (annoated)
Create (1) // main c1 variable
Create (2) // main c2 variable
Create (3) // main c3 variable
before
x=5 y=6
x=1 y=1
x=100 y=200
Start +
Create (4) // operator+ temp
End +
Copy (5) // return value temporary
kill (4)
kill (5)
after
x=5 y=6
x=1 y=1
x=6 y=7
kill (3)
kill (2)
kill (1)
Which

Jul 19 '05 #2

"djskrill" <cp*@twerd.co m> wrote in message
news:f0******** *************** ***@posting.goo gle.com...
Why is the Constructor called 4 times but the Destructor 5 times? I am
using MS VC 6. If this has been covered already please let me know.

The Code:
Please indent your code. It's not very readable without it.
#include <stdio.h>
Why aren't you using iostreams?

class MyClass {
private:
int x;
int y;
static int count;
int id;
public:
MyClass(int x=0,int y=0): x(x),y(y){
printf("Create (%d)\n",++count );
id = count;
}
~MyClass(){
printf("kill (%d)\n",id);
}
MyClass(const MyClass &r){
This is a constructor. A 'copy constructor'.
printf("Copy\n" );
x = r.x;
y = r.y;
You've left 'count' uninitialized.
Evalutating its value will give undefined behavior.
}
Also, why aren't you using initializer list?

MyClass(const MyClass &r) : x(r.x), y(r.y), count(r.count)
{
printf("Copy\n" );
}

More below.

void Set(int ix,int iy){
x = ix; y = iy;
}
void Print(){
printf("x=%d y=%d\n",x,y);
}

//operators
MyClass operator + (const MyClass &left){
printf("Start +\n");
MyClass temp;
temp.x = x + left.x; temp.y = y + left.y;
printf("End +\n");
return temp;
}
MyClass &operator += (const MyClass &left){
x += left.x; y += left.y;
return *this;
}
MyClass &operator += (int left){
x += left; y += left;
return *this;
}
MyClass &operator = (const MyClass &r){
x = r.x; y = r.y;
return *this;
}
};

int MyClass::count = 0;

int main(int argc,char **argv){

MyClass c1(5,6);
MyClass c2(1,1);
MyClass c3(100,200);

printf("before\ n");
c1.Print();
c2.Print();
c3.Print();

c3 = c1+ c2;

printf("after\n ");
c1.Print();
c2.Print();
c3.Print();
return 0;
}


I get output with VC++6.0 SP5:

Create (1)
Create (2)
Create (3)
before
x=5 y=6
x=1 y=1
x=100 y=200
Start +
Create (4)
End +
Copy <<== note that this is a ctor call
kill (4)
kill (-858993460) <<== this alerted me to the 'uninitialized' problem
after
x=5 y=6
x=1 y=1
x=6 y=7
kill (3)
kill (2)
kill (1)
I see five ctor calls, and five dtor calls.

-Mike
Jul 19 '05 #3

"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:%V******** *********@newsr ead4.news.pas.e arthlink.net...
MyClass(const MyClass &r){
This is a constructor. A 'copy constructor'.


After reading Ron's reply, I realized I have erred.
printf("Copy\n" );
x = r.x;
y = r.y;


You've left 'count' uninitialized.


'id'

Evalutating its value will give undefined behavior.
}


Also, why aren't you using initializer list?

MyClass(const MyClass &r) : x(r.x), y(r.y), count(r.count)


MyClass(const MyClass &r) : x(r.x), y(r.y), id(r.id)
Sorry about that. That's what I get for not compiling and
testing my corrections. :-)

-Mike
Jul 19 '05 #4

"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:%V******** *********@newsr ead4.news.pas.e arthlink.net...
Please indent your code. It's not very readable without it.
His code is indented. It's just that your news reader (presumably outlook express)
is eating the tabs on display.


You've left 'count' uninitialized.
Evalutating its value will give undefined behavior.


Actually, he left id uninitialized. Count is a static.
Jul 19 '05 #5

"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:2Z******** *********@newsr ead4.news.pas.e arthlink.net...

MyClass(const MyClass &r) : x(r.x), y(r.y), id(r.id)
Sorry about that. That's what I get for not compiling and
testing my corrections. :-)

Actually, he doesn't want to copy the id. He wants to give it
a new serial number, otherwise it's impossible to pair up the destructors.
Jul 19 '05 #6

"Ron Natalie" <ro*@sensor.com > wrote in message
news:3f******** *************** @news.newshosti ng.com...

"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:2Z******** *********@newsr ead4.news.pas.e arthlink.net...

MyClass(const MyClass &r) : x(r.x), y(r.y), id(r.id)
Sorry about that. That's what I get for not compiling and
testing my corrections. :-)

Actually, he doesn't want to copy the id. He wants to give it
a new serial number, otherwise it's impossible to pair up the destructors.


Oh, yes, overlooked that.

-Mike
Jul 19 '05 #7
"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:<%V******* **********@news read4.news.pas. earthlink.net>. ..
[snip]
MyClass(const MyClass &r){


This is a constructor. A 'copy constructor'.
printf("Copy\n" );
x = r.x;
y = r.y;


You've left 'count' uninitialized.
Evalutating its value will give undefined behavior.
}


Also, why aren't you using initializer list?

MyClass(const MyClass &r) : x(r.x), y(r.y), count(r.count)
{
printf("Copy\n" );
}

but count is static and need not be initialized in constructors. I
believe you meant id. But then again, the proper way would be:

MyClass(const MyClass &r) : x(r.x), y(r.y)
{
++count;
id = count;
printf("Copy create (%d)\n",++count );
}

which would correct two problems: the garbage you get when printing id
at destruction time, and accounting for the construction of the
object.

Regards,

Marcelo Pinto
Jul 19 '05 #8
mp****@tecnolin k.com.br (Marcelo Pinto) wrote in message news:<e3******* *************** ****@posting.go ogle.com>...
"Mike Wahler" <mk******@mkwah ler.net> wrote in message news:<%V******* **********@news read4.news.pas. earthlink.net>. .. [snip] but count is static and need not be initialized in constructors. I
believe you meant id. But then again, the proper way would be:

MyClass(const MyClass &r) : x(r.x), y(r.y)
{
++count;
id = count;
printf("Copy create (%d)\n",++count );

[snip]
forgive me the ++count inside the printf, it should be:
printf("Copy create (%d)\n",count);

Regards,

Marcelo Pinto
Jul 19 '05 #9
Thanks for the help.
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
13230
by: Robin Forster | last post by:
I have two classes: aule_gl_window (parent class) and aule_button (sub class) I want to call the super class (parent) constructor code from the sub class constructor.
6
3019
by: giles | last post by:
Hi, Does a compiler generated constructor initialise the data members? Giles
23
5186
by: Fabian Müller | last post by:
Hi all, my question is as follows: If have a class X and a class Y derived from X. Constructor of X is X(param1, param2) . Constructor of Y is Y(param1, ..., param4) .
3
2430
by: bipod.rafique | last post by:
Hello all, Even though this topic has been discussed many times, I still need your help in clearing my confusions. Consider the following code: class aclass{ public: aclass(){
45
6368
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using parameters, I get CS1501 (no method with X arguments). Here's a simplified example which mimics the circumstances: namespace InheritError { // Random base class. public class A { protected int i;
8
1815
by: JAL | last post by:
According to MSDN2, if a managed class throws an exception in the constructor, the destructor will be called. If an exception is thrown in the constructor the object never existed so how in the world can the destructor of a object that does not exist get called! Here is the MSDN2 document: Code authored in Visual C++ and compiled with /clr will run a type's destructor for the following reasons: ....
14
3217
by: gurry | last post by:
Suppose there's a class A. There's another class called B which looks like this: class B { private: A a; public : B() { a.~A() } }
8
2229
by: Kannan | last post by:
Some amount of memory is allocated inside the Base Constructor using new. During the construction of a derived object an exception occurred in the constructor of the derived class. Will the memory get de allocated which got allocated in Base class constructor? Will the Base class destructor get called? class Base { int *p;
20
432
by: royashish | last post by:
Hi all , A question to the C++ fraternity , Why the Copy constructor ? Was suggested in Effective C++ , In Case the Object contains a Char* , a assignment operator = makes the two object point to the same address . In this case any Of the two Object is destroyed a memory leak occurs as one of the object stays on the Heap . My experiments on the same have proved otherwise .
0
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10501
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10273
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.