1

If static class member and static class function has a class scope then why can't I access the display function(it shows error)? If in place of display function I write count it displays the correct value i.e., 0

#include <iostream> #include <string> using namespace std; class Person { public: static int Length; static void display() { cout<< ++Length; } }; int Person::Length=0; int main() { cout<< Person :: display(); //error // Person :: Length shows correct value return 0; } 

2 Answers 2

5

You can call the display function, your error is that you are trying to output the result to cout. Person::display doesn't return anything, hence the error.

Just change this:

cout<< Person :: display(); //error 

To this:

Person::display(); 
Sign up to request clarification or add additional context in comments.

2 Comments

but why does it work with the static members and not with the static member function? cout<<Person :: Length prints correct value
Because Person::Length is an int. Person::display() returns nothing. You can't output nothing.
0

If you want to pipe objects into streams, you need to define an appropriate operator <<, like this:

#include <iostream> #include <string> using namespace std; class Person { public: class Displayable { template< typename OStream > friend OStream& operator<< (OStream& os, Displayable const&) { os << ++Person::Length; return os; } }; static int Length; static Displayable display() { return {}; } }; int Person::Length=0; int main() { cout<< Person :: display(); //works // Person :: Length shows correct value return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.