length/width in a Rectangle — every object has its own values)static, shared across all objects of the class — one copy total, not one per objectRectangle(double l, double w) : length(l), width(w) {}) over assigning inside the constructor body — more efficient, and required for const/reference membersclass Counter
{
private:
static int count; // ONE shared copy across all objects
public:
Counter() { count++; }
static int getCount() { return count; }
};
int Counter::count = 0; // static members must be defined outside the class too
MCQ Trap:
staticmembers belong to the class (one shared copy); non-static (instance) members belong to each object separately.
#include <iostream>
using namespace std;
class Counter
{
private:
int id; // instance member -- each object has its own
static int count; // static member -- ONE shared copy for the whole class
public:
Counter()
{
count++; // increments the SHARED copy
id = count; // this object's own personal id
}
void show()
{
cout << "My ID: " << id << ", Total objects created: " << count << endl;
}
};
int Counter::count = 0; // static members MUST be defined outside the class (once, at file scope)
int main()
{
Counter a, b, c;
a.show(); // My ID: 1, Total objects created: 3
b.show(); // My ID: 2, Total objects created: 3
c.show(); // My ID: 3, Total objects created: 3
return 0;
}
Notice count is the same value (3) across all three objects — because there's only one shared copy — while id is different for each, since it's an instance member.
class Point
{
private:
const int x; // const member -- MUST be set at construction, can't be assigned later
public:
Point(int val) : x(val) {} // initializer list -- the ONLY way to set a const member
// Point(int val) { x = val; } -- ERROR: cannot assign to a const member in the constructor body
};
static data member is:
const data member can only be initialized via:
Counter example, after creating 5 Counter objects, the static count will equal:
static data members be defined a second time outside the class?const data member require an initializer list instead of body assignment?Counter example, what would count be after creating 5 objects?