Good Afternoon,

I'm having a little trouble with a class. The error that I'm getting is: a nonstatic member reference must be relative to a specific object in the function void B::printStatic() { cout<<"size is "<<size<<endl; Here is the code that I have.

#include <iomanip>
#include <iostream>
#include <string>

using namespace std;

class  B
 //const int cnt; 
 static int lifeCount; 
 static int deathCount; 
 const int size;   
 char *cat; 
 B(const int n);    
 void print();   
 static void printStatic();

int B::lifeCount=0;    
int B::deathCount=0; 

 cat = new char[size]; 
 strcpy(cat, "I see a head initialization."); 

B::B(const int n): size(n)
 cat = new char[n]; 
 if (n>50)
  strcpy(cat, "Meow, meow, another head initialization.");

void B::print()
 cout<<"size is => "<< size<<endl; 
 cout<<"cat is => " <<cat<<endl; 

 delete[] cat; 

void B::printStatic() 
 cout<<"size is " <<size<<endl;
 cout<<lifeCount<<"  many class B objects "
     <<"have been created up to this point."<<endl; 
 cout<<deathCount<<"  many class B objects have "
     <<"died up to this point."<<endl; 

int main()

return 0;

You try to print size from a static member function, but size isn't a static member. To access non-static members, you need an object, because that's where memory for non-static members is allocated.

I can't walk you through it because what you're doing isn't meaningful. size is an instance member, which means you must have created an object somewhere and given size a value that warrants outputting it.

I don't think you should be printing size from printStatic() at all, so my suggestion would be to remove that line entirely. It's already being printed from print(), so what's the point?

This question has already been answered. Start a new discussion instead.