In: Computer Science
write a C++ program to CREATE A CLASS EMPLOYEE WITH YOUR CHOICE
OF ATTRIBUTES AND FUNCTIONS COVERING THE
FOLLOWING POINTS:
1) COUNTING NUMBER OF OBJECTS CREATED ( NO OBJECT ARRAY TO BE USED)
USING ROLE OF
STATIC MEMBER
2) SHOWING THE VALID INVALID STATEMENTS IN CASE OF STATIC MEMBER
WITH NON STATIC
MEMBER FUNCTION, NON STATIC MEMBERS OF CLASS WITH STATIC MEMBER
FUNCTION, BOTH
STATIC. SHOW THE ERRORS WHERE STATEMENTS ARE INVALID.
3) CALL OF STATIC MEMBER FUNCTION, DECLARATION OF STATIC
VARIABLE.
4) STATIC OBJECTS : HOW TO USE; WHERE TO USE
5) CAN STATIC MEMBER FUNCTION BE USED FOR INVOKING ANY CONSTRUCTOR
OF THE CLASS.
6) STATIC MEMBER FUNCTION TO INVOKE PRIVATE CONSTRUCTOR
Static Objects:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.Static objects are declared with the keyword static. They are initialized only once and stored in the static storage area. The static objects are only destroyed when the program terminates i.e. they live until program termination.The static data member is always initialized to zero when the first class object is created. static data_type data_member_name; In the above syntax, static keyword is used.
We can invoke private constructor using static member function of class.
#include <iostream>
using namespace std;
class Employee
{
public:
static Employee createA() { return Employee(0); }
static void dosomething(Employee *a) { return a->something();
}
Employee()
{
Id=++objcnt;
}
~Employee()
{
--objcnt;
}
void printIdNumber(void)
{
cout<<"Id Number :"<<Id<<"\n";
}
static void printIdCount(void)
{
cout<<"Count :"<<objcnt<<"\n";
}
private:
Employee (int x) { cout << "ctor" << endl; }
void something() { cout << "something" << endl; }
int Id;
char Name[25];
int Age;
long Salary;
static int objcnt;
public:
void GetData();
void PutData();
};
int Employee::objcnt;
int main(void)
{
Employee a = Employee::createA();
Employee::dosomething(&a);
Employee e1,e2; //Statement 3 : Creating Object
Employee::printIdCount();
Employee e3;
e1.printIdNumber();
e2.printIdNumber();
return 0;
}