Static Function Members:
By
declaring a function member as static, you make it independent of any
particular object of the class. A static member function can be called even if
no objects of the class exist and the static
functions are accessed using only the class name and the scope
resolutionoperator ::.
A static
member function can only access static data member, other static member
functions and any other functions from outside the class.
Static
member functions have a class scope and they do not have access to the this pointer of the class. You could
use a static member function to determine whether some objects of the class
have been created or not.
Let us
try the following example to understand the concept of static function members:
#include<iostream>
usingnamespacestd;
classBox
{
public: staticintobjectCount;
// Constructor definition
Box(double l=2.0,double b=2.0,double h=2.0)
{
cout<<"Constructor
called."<<endl; length= l;
breadth= b;
height= h;
// Increase every time object is created
objectCount++;
}
doubleVolume()
{
return length * breadth * height;
}
staticintgetCount()
{
returnobjectCount;
}
private:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box };
// Initialize static member of class Box
intBox::objectCount=0;
int main(void)
{
Print total number of objects before creating object.
cout<<"Inital Stage Count: "<<Box::getCount()<<endl;
BoxBox1(3.3,1.2,1.5);// Declare box1
BoxBox2(8.5,6.0,2.0);// Declare box2
// Print total number of objects after creating object.
cout<<"Final Stage Count: "<<Box::getCount()<<endl;
return0;
}
When the
above code is compiled and executed, it produces the following result: InitalStageCount:0
Constructor called.
Constructor called.
FinalStageCount:2
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.