Hello!
Im writing a program to practice creating objects/classes.
I only ran into one problem which is when I try to create my print function. I want to create a function in my separate file that prints the objects attributes that I can call but it wont let me create it without an object. How do I fix this?
Thanks!
This is the function;
1 2 3 4 5 6
void SkrivUt(){
std::cout << "Race: "<< Cat::getRace() << "Character: " << Cat::getCharacter() << "Age: " << Cat::getAge();
}
I get the error message cannot call getRace.. getCharacter.. etc without member object.
I'm guessing all of those functions aren't static.
You made a class called Cat, which is a type. A possible simile is that a class is like a blueprint for an object. It describes your object. Now, to actually use getRace and such, you need to actually have an object to call them from. The distinction here is similar to the difference between int (the type), and a variable of type int.
An example might look something like this.
1 2 3
Cat kitty;
//Do stuff to the kitty.
std::cout << "The kitty is " << kitty.getAge() << " year(s) old!\n";
Note that you can pass objects to functions and return them from functions like any other variable. Small complication: it may be better to have const references to objects as parameters if you don't need or want to copy them.
Only static class functions can be called without an object using the Class::function() syntax.
So, you should add static as a keyword to the definition of your functions inside the Cat class.
However, you probably *don't* want to do this. Is every cat the same race, character, age? I'm assuming not, since that would be kinda useless. You probably do want to pass an instance of a Cat into your print function.
Hey! Thanks for your answers. Indeed they do not have the same attributes! But I would like to create a function that I can call whenever Ive created an object and want to print its attributes, what would be the best way of going about this?
Ohh, turns out all that was missing was the Cat:: in front of function haha, duh... palms were faced. Much thanks for all your help tho, hopefully I can go to bed soon hah. ^^