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
{
private: 
 //const int cnt; 
 static int lifeCount; 
 static int deathCount; 
 const int size;   
 char *cat; 
public: 
 B();     
 B(const int n);    
 void print();   
 static void printStatic();
 ~B();     
}; 

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

B::B():size(100)   
{
 lifeCount++;   
 cat = new char[size]; 
 strcpy(cat, "I see a head initialization."); 
}

B::B(const int n): size(n)
{ 
 lifeCount++;   
 cat = new char[n]; 
 if (n>50)
  strcpy(cat, "Meow, meow, another head initialization.");
 else
  cat[0]='\0';
}

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

B::~B()
{
 deathCount++;    
 printStatic();   
 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.

Deceptikon,

would this work
B.size;
cout<<"size is"<<B.size>>endl;

No, B is a class, not an object.

how about
B tiger;
Can you walk me through.

Thanks

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?

thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.