With respect to the following code segment, what should be the n value in different classes, e.g., what is a.n, b[2].n, and c->n

How to analyze them?

#include <iostream>
using namespace std;

class CDummy
{
public:
    static int n;
    CDummy(){ n++ ;};
    ~CDummy(){ n--; };
};

int CDummy::n = 0;
int main()
{
    CDummy a;
    CDummy b[5];
    CDummy*c = new CDummy;
system("PAUSE");
    return 0;
}

Recommended Answers

All 2 Replies

First of all, n will be the same in all instances at a specific time since it is a static variable. n is increased when a CDummy object is created and n is decreased when an object is deallocated. You are creating 7 CDummy objects and therefore n is 7 when all objects have been constructed.

may want to initilize the static variable to 0 to start with.

It will have a positive value while instances of the class exist, otherwise 0.

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.