Sign in to follow this  

calling a member function from a class without creating an object?

This topic is 4515 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey all. Um...down 2 busneiss. I have a linked lists system. In my main i have a switch statement, One of the options is to display the list, but when i include the function it says something about static functions. Okay i no that this error is comming up because i havent created a object yet. I have tried playing around with the static keyword but it hasnt helped much. I then thought of testing so see if there is a next node by seing if the next element is == NULL. LOL..now with this it says that pHead, which is the head doesnt exist. Now i no that this is because i havent created an object. heres my code:
				if(!pHead ==NULL)
				{
					cout << "error Please create a soldier first" << "\n";
					break;
					goto start;								//goto the start of the switch statement and get users input again.
				}
				else
				{
				Node::Display();
				}
okay this code is right at the top of main, now i was wondering if there is a way to somehow do this without creating an object. thankz for any help :)

Share this post


Link to post
Share on other sites
Quote:
if(!pHead ==NULL)


I think this evaluates to

if ((!pHead) == NULL)

Since !0 is equal to 1 and !1 is equal to 0, it will evaluate the opposite of what you want, every time. Rewrite it as

if (pHead != NULL)

Not sure if this is the problem, and it'd be nice to see the exact errors you are getting, but this is what I noticed.

Share this post


Link to post
Share on other sites
btw thankz 4 the reply ;0.

here is the error i'm getting:

error C2352: 'Node::Display' : illegal call of non-static member function


okay i no that this error is because i havent created an object, but the thing is i dont want to create one , the display function should only be called when an object is created, thats y i tested if pHead = NULL.


case 3:
cout << "You have choosen to Display Soldiers." << "\n";
cout << "Launching Request";
Sleep(700);
cout << ".......";
Sleep(500);
cout << ".......";
Sleep(300);
cout << ".....Done!" << "\n";
if(pHead !=NULL) // tests to see if there is another object, if not then it displays an error message and returns to start
// this is usefull because without this then if the user tried to check the soldiers stats without actually creating
// any object then it would result in the program crashing.
{
cout << "error Please create a soldier first" << "\n";
goto start;
break;
//goto the start of the switch statement and get users input again.
}
else
{
Node::Display();
}
break;


that is the total switch case.
Now i need 2 find a way to call this Display function.
because when i compile the program it states the above error.

here is the display function in the class:

this is in public btw:
void Display();


here is the display functions implementation:

void Node::Display() //Display function is from Node class so instance it.
{

if(itsSoldier->GetKills() > 0 && GetNext()) // stops the pHead from showing and gets the nextSoldier
{
cout << "**************************************\n";
cout << "Soldiers Nickname: " << itsSoldier->GetNickname() << "\n";
cout << "Soldiers Email Adddress: " << itsSoldier->getEmailAddress() << "\n";
cout << "Soldiers Total Kills: " << itsSoldier->GetKills() << "\n";
cout << "Soldiers Cash Balance: " << "$" << itsSoldier->getCash() << "\n";
cout << "Soldiers Rank: " << itsSoldier->getRank() << "\n";
cout << "**************************************\n";

}
if(itsNext)
{
itsNext->Display();
}
}

okay....now i no that the error is there is no object created.
This is because no data has been entered yet.
Just wondering what i can do to make this work???

thankz

Share this post


Link to post
Share on other sites
if you want to call the display method without an object you have to make it a static function:

static void Display();

then you can call it like

myClass::Display()


Jon

Share this post


Link to post
Share on other sites
Ok.

You can use this statement if(pHead) instead of that if(pHead != Null)


try this.


if(pHead)
{
yada yada yada
}
else
{
Node.Display(); // instead of Node::Display
}

but have you created the object yet?

Share this post


Link to post
Share on other sites
cheerz all.

umm..now when i change it 2 static i get:

error C2227: left of '->Display' must point to class/struct/union


Okay i have modified the code, so that its all in the display function.
Now i get the above error for every time it tries to access data from the list.

here is the modified code:

void Node::Display() //Display function is from Node class so instance it.
{
if(itsNext == NULL)
{
cout << "error Please create a soldier first" << "\n";
}
else
{
if(itsSoldier->GetKills() > 0 && GetNext()) // stops the pHead from showing and gets the nextSoldier
{
cout << "**************************************\n";
cout << "Soldiers Nickname: " << itsSoldier->GetNickname() << "\n";
cout << "Soldiers Email Adddress: " << itsSoldier->getEmailAddress() << "\n";
cout << "Soldiers Total Kills: " << itsSoldier->GetKills() << "\n";
cout << "Soldiers Cash Balance: " << "$" << itsSoldier->getCash() << "\n";
cout << "Soldiers Rank: " << itsSoldier->getRank() << "\n";
cout << "**************************************\n";

}

}
}


I changed pHead to itsNext, which sets up the next soldier.
Thus the end of the list is null so it should work.

Just wondering y that the full if statement is being processed when its set up "i think it is" to only display the soldiers if there is one created.

Thankz very much for the help so far :)

Share this post


Link to post
Share on other sites
If you're trying to use a member function which references non-static member variables, logically, you MUST have an instance.

Think about it - you're accessing members of a cNode in your display function. These members are "inside" a cNode "box". If you don't say which cNode "box" you want to display, your compiler won't know what to do.

You cannot call a member function like this without an object - you must have an object.

cNode node;
node.Display();

I'd suggest since you're not used to OOP, that you don't use it until you have some more experience. And you might want to consider using STL's list implementation, it'd be a lot easier than writing your own.

Share this post


Link to post
Share on other sites
Quote:
Original post by Mushu
If you're trying to use a member function which references non-static member variables, logically, you MUST have an instance.

Think about it - you're accessing members of a cNode in your display function. These members are "inside" a cNode "box". If you don't say which cNode "box" you want to display, your compiler won't know what to do.

You cannot call a member function like this without an object - you must have an object.

cNode node;
node.Display();

I'd suggest since you're not used to OOP, that you don't use it until you have some more experience. And you might want to consider using STL's list implementation, it'd be a lot easier than writing your own.


okay thankz for the help.
But the reason i had the if statement was to check if an object was created.
the display code shouldnt be run until there is an object created.
if that makes more sence.

if you check the updated display function there is a clause to see if there is an object, but some reason its checking the code on the else bit.

Okay i created a temporary node:
Node tempNode

i then called tempNode.display();

okay that works but now my constructor is bogus.

the thing i want 2 do is only run the display function when an objects created.

the switch statement is the main menu of the program and thus option 3 is to display the soldiers, so i need to have the display function on option 3.
That was the reason for using the if statement

cheerz.

Share this post


Link to post
Share on other sites
Quote:
Original post by Mushu
Well, then the only advice I can give you is to refactor your code, unless you have a specific problem to address.



My code is refractored, its all broken up into h files & different c++ files.

Thankz 4 ur help btw.

Umm...i think that i will remove the display soldier option...
and only use the display soldier option after certain events.
So when you create a soldier then it will display.
I had this working before.
Okay thankz again 4 ur help all

P.S just made it back 2 how it was, after a soldier object is created then it runs the display function.

I just thought that having a function that displayed all soldiers accessible from the main menu would be snazzy //)

Share this post


Link to post
Share on other sites
Quote:
Original post by silverphyre673
Quote:
if(!pHead ==NULL)


I think this evaluates to

if ((!pHead) == NULL)

Since !0 is equal to 1 and !1 is equal to 0, it will evaluate the opposite of what you want, every time. Rewrite it as

if (pHead != NULL)

Not sure if this is the problem, and it'd be nice to see the exact errors you are getting, but this is what I noticed.


it can be condensed further

if(pHead)
{
...
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Shouldn't it be:

if(!pHead)
{
// Node does not exist, so display an error.
cout <

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Sorry, messed the message up. Here it is again.

if(!pHead)
{
// Node does not exist, so display an error
}
else
{
// Node exists, so display it
Node::Display();
}

Share this post


Link to post
Share on other sites
Okay.

So you're using some kind of linked list that you've written?

I personally wouls recommend using the std::list<> provided container. Why reinvent the wheel. And, no offence, but it is possibly better/more efficient than anything we can hand craft. It hass been around for years and has been fully optimised etc.

Also you say that you're testing if the object has been created...perhaps a better way would be to set a use static boolean inside your class.

Testing for (!phead) doesn't test if teh class has been instansiated but if the head of teh linked list is populated...there is a difference.


class aClass
{
public:
aClass():isCreated(true){}
~aClass(){}
static bool Created(){return isCreated == true;)
static bool isCreated;
}

static bool isCreated = false;




Anyhow, hope this helped and good luck..:)

[Edited by - garyfletcher on August 4, 2005 1:49:22 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Twinsen2
My code is refractored, its all broken up into h files & different c++ files.


Sorry to destroy any illusions you may have, but there is far, far more to refactoring than that.

Anyway, here's the problem: which "node" exactly would you like to "display", and in which circumstances? It looks to me like you're saying "error, have to create a soldier first" if the head pointer is *not* null, i.e. if there *is* a node (which contains a soldier), which is backwards... and then if the pointer is null, i.e. there are no nodes and thus no soldier, you then want to display a node without having any particular one in mind, which is also backwards.

But beyond that, I can 100% guarantee that the surrounding code is *full* of bugs.

First, use std::list (or, for that matter, any standard "container"; who knows which is most appropriate for your task? Not us; we can't see enough of your project to tell you). It's easy to work with, and is correct. Pretty much noone who is actually really capable of doing this stuff correctly wants to do it themselves, which is why it's in the standard library for you.

Second, please make the soldier responsible for printing itself, rather than letting other people grab all its data and then have to print it themselves. That's also backwards in a different way - poor encapsulation. In the real world, if your sink is leaking, would you call a plumber, wait for him to arrive, then take his tools, fix the sink yourself and give them back? Of course not; you'd pay him to fix the sink, because that's his job.


// Implementing the printing within the soldier properly
void Soldier::print(ostream& os) const {
// Since this is a member function of the Soldier, we have access to the
// current Soldier's internals. This is the whole idea with OO; if you have
// to jump through hoops and barrels in order to keep data private and still
// get at it, then the code is *in the wrong place*.
// Note we make this a const member function, to inform the compiler that
// the Soldier will not be "changed" by the printing process.
os << "**************************************\n"
<< "Soldiers Nickname: " << myNickname << "\n"
<< "Soldiers Email Adddress: " << myEmailAddress << "\n"
<< "Soldiers Total Kills: " << myKills << "\n"
<< "Soldiers Cash Balance: $" << myCash << "\n"
<< "Soldiers Rank: " << myRank << "\n"
<< "**************************************\n";
// That's all one statement, by the way.
// Also note how we take in an ostream as a parameter; that tells us where
// to write to, so that we're not limited to printing to console.
}

// Now we can add some syntactic sugar, that will let us use an ostream's
// operator<< to output a Soldier.
ostream& operator<<(ostream& os, const Soldier& s) {
// The Soldier parameter is passed by const reference because it's an
// object that will not be changed by the printing process.
s.print(os); // invoke the printing functionality
return os; // and allow for "chaining".
}

std::list<Soldier> mySoldiers;
typedef std::list<Soldier>::iterator SoldierIterator;

// to test if there are any soldiers
if (mySoldiers.empty()) { /* there are none; report an error */ }
else {
// to print the first soldier, using the soldier's function for it
mySoldiers.front().print(cout);
// or we could take advantage of the syntactic sugar
cout << mySoldiers.front();
// to print all the soldiers
for (SoldierIterator si = mySoldiers.begin(); si != mySoldiers.end(); ++si) {
si->print(cout);
// iterators behave like pointers; "dereferencing" them yields an object.
// And again we could also do it this way
cout << *si;
}
}

Share this post


Link to post
Share on other sites

This topic is 4515 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this