static function print static object

Hello.I have an exercise:

Create a class containing an int, a constructor that initializes the int from its argument, and a print( ) function to display the int. Now create a second class that contains a static object of the first one. Add a static member function that calls the static object’s print( ) function. Exercise your class in main( ).

First class is OK,but second is problem.

#include <iostream>
using namespace std;
class I
{
int a;
public:
I(int i):a(i){};
void printi(){cout<<a<<endl;}
};
class S
{
static I obj;
public:

static void f(){}

};
I S::obj=2;
int main()
{
I o(1);
o.printi();

getchar();
}
What problem?

Your S::f() does not call I::printi().
Your main() does not call S::f().
Remove I from the line that initializes the S::obj.
Thanks.When I remove I from the line I S::obj an error occurs. This version works.

#include <iostream>
using namespace std;
class I
{
int a;
public:
I(int i):a(i){};
void printi(){cout<<a<<endl;}
};
class S
{
static I obj;
public:

static void f(){obj.I::printi();}

};
I S::obj=2;
int main()
{
I o(1);
o.printi();
S::f();
getchar();
}
Topic archived. No new replies allowed.