Answer to Question #188858 in C++ for Ahmad Raza

Question #188858

Write a Program in C++ which completes following requirements:

a. Create a class, having a static function printing some information 

and invoke that method using scope resolution operator.

b. Try to access non-static data members from static method and 

write in comments what happens.

c. Declare and initialize a static variable as counter in a function

(increment it in every call) and call it multiple times printing the 

change in value

d. Write about your observations while making this assignment in a 

word file about static variables and static methods.


1
Expert's answer
2021-05-04T05:23:00-0400


#include<iostream>
#include <stdio.h>
#include <string>
using namespace std;


class A{


	static int b;
//	int a;
	
public:
	static int count;
	//Static function
	static int GetValue(){
		b = 10;
		return b;		
	}
	
//	static int getValue(){
//		a = 10;
//		return a;		
//	}


	static int totalCount()
	{
		return ++count;
	}


};


//initialize static variable
int A::b=5 ;
int A::count=0;


int main(){
	
	A obj1, obj2;
//	Static function can access only static variable


//	In below statement, we have a static variable b of int type and have initialize to 5, 
//	but inside static function the value of static variable b has been modified to 10.
//	Hence, program will work correctly.
	cout<<"Value of a is : "<< A::GetValue()<<endl;
	
//	In below statement, compiler will flash an error i.e. illegal reference to non-static member A::a
//	cout<< A::getValue();


	cout<<"Value of count for 1st function call : "<<A::totalCount()<<endl;
	cout<<"Value of count for 2nd function call : "<<A::totalCount()<<endl;
	cout<<"Value of count for 3rd function call : "<<A::totalCount()<<endl;
	cout<<"Value of count for 4th function call : "<<A::totalCount()<<endl;
	
	return 0;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS