Static data members of a class occupy memory once whereas non static data members occupy members as per the number of objects created. Justify the statement by writing a program.
When a member of class is declared as static, we only have a copy of the static member regardless of number of objects created as illustrated by the following c++ program
#include <iostream>
using namespace std;
class My_Box {
public:
static int numOfObjects;
// Here, you create a constructor having same name as the class
My_Box(float l = 1.0, float w = 1.0, float h = 1.0) {
cout <<"The Constructor call to initialize objects as they are created " << endl;
length = l;
width = w;
height = h;
// The numOfObjects increments at every time an object is created
numOfObjects++;
}
float Volume() {
return length * width * height;
}
private:
float length;
float width;
float height;
};
// Initialization of class static member of class
int My_Box::numOfObjects = 0;
int main(void) {
My_Box FirstBox(2.1, 6.2, 1.5);
My_Box SecondBox(11.5, 5.5, 2.0);
// Display sum of objects created.
cout << "Total objects: " << My_Box::numOfObjects << endl;
return 0;
}
On the other hand, non static data members occupy members as per the number of objects created as illustrated by the program bellow
#include <iostream>
class NonStaticDemo
{
private:
int x { 5 }; // << wow!
int y { 5 }; // << wow2!
std::string Myname { "Sample namee" }; // wow3!
public:
NonStaticDemo() {
std::cout << "NonStaticDemo {" << x << ", " << y << ", \"" << Myname << "\"}\n";
}
~NonStaticDemo() { std::cout << "NonStaticDemo::destructor\n"; }
};
int main()
{
NonStaticDemo sampleObject;
}
Comments
Leave a comment