C++ prgramming - Templates and Static
Create a class called fun.
Add to the class a static integer variable called count.
Add a constructor that has count++;
Add a function getCount() { return count ; }
Instantiate 4 instance of the class. F1, F2, F3 and F4.
Print out the value of count for each instance.
-Be sure to include a UML
What do you note about the static variable called count? (Answer the question)
#include <iostream>
using namespace std; // consider removing this line in serious
projects
class fun{
public:
static int count;
fun(); //creating constructor
int getcount(){
return count;
}
};
int fun::count = 0;
fun::fun () {
cout<<count++<<endl;
}
int main() {
fun f1;
fun f2;
fun f3;
fun f4;
cout<<f1.getcount()<<endl;
cout<<f2.getcount()<<endl;
cout<<f3.getcount()<<endl;
cout<<f4.getcount()<<endl;
return 0;
}
----------------------------------------end of program--------------------------------------------
//output
0 1 2 3 4 4 4 4
-----------------------------end of output-----------------------------------------------------------------------
Explaination:
Whenever we create an instance of a class fun(f1,f2,f3,f4),
first the constructor of the class is
called which prints the count value: 0,1,2,3 (for four instances of
class).
Now, as we call f1.getcount() , it prints increment value of count
i.e. 4.
As we call f2.getcount() , it prints value of count i.e. 4.
Same happens for f3 nd f4.
-----------------------------------------------------------end of explaination-----------------------------------------------------------
Uml: class diagram
FUN() |
---|
count:int |
fun(); getcount(): |
Get Answers For Free
Most questions answered within 1 hours.