Hi.

I have a class named Product, each object of this class holds one product in a "store". The class also has a static int member to keep track of how many products there are.

iProducts is static member.

Constructor:

Product::Product(std::string name, int price, std::string description)
{
	sName = name;
	iPrice = price;
	sDescription = description;

	iProducts++;
}

Destructor:

~Product() {iProducts--;};

Is this a correct way of doing this?

Because the destructor gives -- right away when I define a new object of the class. The destructor should only run when object is deleted right?

Example:

Product milk = Product( "Milk", 7 , "Lot's of calcium");
Product mustard = Product( "Mustard", 35, "Very exclusive and good" );

cout << Product::iProducts;

Shows 0, if I don't use -- in constructor it gives me the correct 2.

try having the destructor output something, and outputting iProducts in various places, like at the beginning and between the two constructions. :D

Okey, I did, and it clearly shows that the destructor is run when i define objects.

I edited constructor and destructor to cout like so:

Product::Product(std::string name, int price, std::string description)
{
	sName = name;
	iPrice = price;
	sDescription = description;

	iProducts++;

	std::cout << std::endl << "Constructing, iProducts: " << iProducts << std::endl;
}

Product::~Product() 
{
	iProducts--;
	std::cout << std::endl << "Destructing, iProducts: " << iProducts << std::endl;
};

When I do this:

Product milk = Product( "Milk", 7 , "Lot's of calcium");
Product mustard = Product( "Mustard", 35, "Very exclusive and good" );

Console outputs this:

Constructing, iProducts: 1
Destructing, iProducts: 0
Constructing, iProducts: 1
Destructing, iProducts: 0

What the hell?

I think it has to do with the declarations of the items

Product milk = Product( "Milk", 7 , "Lot's of calcium");

Left side of the assignment operator creates the object. Right side of the assignment operator creates a temporary instance of the object, which gets assigned to the one on the left. Destructor gets called when the temp object is destroyed, decrementing the counter, even though you still have an object.

I thought those declarations odd when you first posted this problem, and now we see a good reason to do it in a more common (normal?) fashion

Product milk ( "Milk", 7 , "Lot's of calcium");

I'm not sure that having a copy constructor will even fix this, because it's only a problem when items are created, not when a normal copy would occur.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.