Answer to Question #189169 in C++ for Uzair Ali

Question #189169

Q1:

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-04T17:28:59-0400

a)

#include <iostream>
using namespace std;
class Temp{
    public:
    Temp(){}
    static void Method(){
        cout<<"Something";
    }
};
int main(){
    Temp::Method();
    return 0;
}

b)

#include <iostream>
using namespace std;
class Temp{
    int n;
    public:
    Temp(){}
    static void Method(){
        cout<<n; //A nonstatic member reference must be relative to a specific object. Compilation fails
    }
};

c)

#include <iostream>
using namespace std;
int demo(){
    static int n = 0;
    return n++;
}
int main(){
    cout<<demo()<<endl;
    cout<<demo()<<endl;
    cout<<demo()<<endl;
    return 0;
}

d) Static methods cannot access ordinary data members

Static variables maintain the value they had on the previous call


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